py 推导式
是的,推导式(comprehension)是一种简洁的语法模式,用于从一个可迭代对象生成新的数据结构。推导式可以用于列表、字典、集合等数据结构。它们的主要特点是将一个可迭代对象中的元素通过某种规则映射到新的数据结构中,并且这种规则可以包含条件过滤。
推导式的类型
- 列表推导式(List Comprehension)
- 字典推导式(Dictionary Comprehension)
- 集合推导式(Set Comprehension)
- 生成器表达式(Generator Expression)
列表推导式
列表推导式用于创建新的列表。其基本语法如下:
[new_element for item in iterable if condition]
示例:
numbers = [1, 2, 3, 4, 5]
squares = [n ** 2 for n in numbers]
print(squares) # 输出: [1, 4, 9, 16, 25]
带条件过滤的列表推导式:
even_squares = [n ** 2 for n in numbers if n % 2 == 0]
print(even_squares) # 输出: [4, 16]
字典推导式
字典推导式用于创建新的字典。其基本语法如下:
{key_expression: value_expression for item in iterable if condition}
示例:
pairs = [
{"token": "BTC", "value": 45000},
{"token": "ETH", "value": 3000},
{"token": "XRP", "value": 1}
]
table_data = {pair["token"]: "0.00000000" for pair in pairs}
print(table_data) # 输出: {'BTC': '0.00000000', 'ETH': '0.00000000', 'XRP': '0.00000000'}
带条件过滤的字典推导式:
filtered_data = {pair["token"]: "0.00000000" for pair in pairs if pair["value"] > 1000}
print(filtered_data) # 输出: {'BTC': '0.00000000', 'ETH': '0.00000000'}
集合推导式
集合推导式用于创建新的集合。其基本语法如下:
{expression for item in iterable if condition}
示例:
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_squares = {n ** 2 for n in numbers}
print(unique_squares) # 输出: {1, 4, 9, 16, 25}
生成器表达式
生成器表达式用于创建生成器。其基本语法与列表推导式类似,但使用圆括号:
(expression for item in iterable if condition)
示例:
numbers = [1, 2, 3, 4, 5]
squares_gen = (n ** 2 for n in numbers)
for square in squares_gen:
print(square)
# 输出:
# 1
# 4
# 9
# 16
# 25
总结
推导式是一种高效、简洁的语法模式,用于从一个可迭代对象生成新的数据结构。通过推导式,你可以在一行代码中完成复杂的映射和过滤操作,从而提高代码的可读性和简洁性。