Files
2025PY/day23/03-推导式的练习.py
2025-05-22 16:50:44 +08:00

48 lines
1.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 题目 1列表推导式字符串操作
# 要求:将字符串 "Hello World" 中的每个字符转换为 ASCII 码值,并生成列表。
# 示例输出:[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
ascii_values = [ord(c) for c in "Hello World"]
# 题目 2字典推导式反转键值对
# 要求:将字典 {'a': 1, 'b': 2, 'c': 3} 的键值对反转,生成新字典。
# 示例输出:{1: 'a', 2: 'b', 3: 'c'}
original_dict = {'a': 1, 'b': 2, 'c': 3}
reversed_dict = {v: k for k, v in original_dict.items()}
# 题目 3集合推导式筛选唯一元素
# 要求:从列表 ['apple', 'banana', 'apple', 'cherry', 'banana'] 中提取所有唯一的水果名称(忽略大小写),并生成集合。
# 示例输出:{'apple', 'banana', 'cherry'}
fruits = ['apple', 'banana', 'apple', 'cherry', 'banana']
unique_fruits = {f.lower() for f in fruits}
# 题目 4嵌套推导式矩阵转置
# 要求:使用列表推导式将矩阵 [[1, 2, 3], [4, 5, 6]] 转置。
matrix = [[1, 2, 3], [4, 5, 6]]
transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
# 题目 5条件推导式筛选和转换
# 要求:从列表 [1, -2, 3, -4, 5, -6] 中筛选出正数,并将每个正数平方后生成新列表。
# 示例输出:[1, 9, 25]
numbers = [1, -2, 3, -4, 5, -6]
squared_positives = [x**2 for x in numbers if x > 0]
# 题目 6字典推导式统计字符频率
# 要求:统计字符串 "hello" 中每个字符的出现次数,生成字符到频率的映射。
# 示例输出:{'h': 1, 'e': 1, 'l': 2, 'o': 1}
s = "hello"
char_freq = {c: s.count(c) for c in s}