注意 :列表推导式的方括号内包含以下内容:一个表达式,后面为一个 for 子句,然后,是零个或多个for或 if 子句。结果是由表达式依据 for 和if 子句求值计算而得出一个新列表。
python复制代码
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
"""
上述推导式等同于:
combs = []
for x in [1,2,3]:
for y in [3,1,4]:
if x != y:
combs.append((x, y))
combs
"""
# 输出 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
2.2 示例及应用
python复制代码
"""
筛选和转换数据:
列表推导式允许你根据特定的条件从一个列表中选择或转换元素,从而创建一个新的列表。例如,你可以过滤出所有的偶数或将列表中的字符串转换为大写。
"""
# 筛选偶数
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)
# 过滤出字符串列表中长度大于3的单词
words = ['python', 'is', 'awesome', 'and', 'fun']
long_words = [word for word in words if len(word)>=3]
print(long_words)
# 转换字符串为大写
words = ['hello', 'world', 'python']
upper_words = [word.upper() for word in words]
print(upper_words)
运行效果:
python复制代码
"""
生成序列:
通过列表推导式,你可以用一行代码生成各种序列,如数字序列、字符序列等。
"""
# 生成平方序列
squares = [x**2 for x in range(5)]
print(squares)
# 生成字符序列
chars = [char for char in 'python']
print(chars)
运行效果:
python复制代码
"""
嵌套迭代:
列表推导式支持嵌套,可以用来创建嵌套结构的数据,例如二维列表。
"""
# 创建二维列表
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix)
# 生成一个包含 3 行 4 列的二维列表,每个元素都是其行索引和列索引的和
matrix_o = [[row + col for col in range(4)] for row in range(3)]
print(matrix_o)
运行效果:
python复制代码
"""
使用复杂的表达式和嵌套函数
"""
from math import pi
[str(round(pi,i)) for i in range(1,6)]
tuple_variable = (expression for item in iterable if condition)
1.expression 是生成元组元素的表达式。
2.item 是可迭代对象中的每个元素。
3.iterable是一个可迭代对象,例如列表、字符串等。
condition是一个可选的条件,用于过滤元素。
3.2 示例及应用
python复制代码
"""
创建元组序列:
当需要生成一个元组序列时,元组推导式是一种简洁的方式。例如,可以使用元组推导式创建包含某种规律的数字、字符串或其他元素的元组序列。
"""
# 生成包含平方数的元组序列
squares_tuple = tuple(x**2 for x in range(5))
print(squares_tuple)
运行效果:
python复制代码
"""
转换数据:
当有一个可迭代的对象,并希望将其转换为元组时,可以使用元组推导式。这在处理数据时很常见。
"""
# 将字符串长度转换为元组
words = ['apple', 'banana', 'orange']
lengths_tuple = tuple(len(word) for word in words)
print(lengths_tuple)
运行效果:
python复制代码
"""
过滤数据:通过添加条件语句,可以使用元组推导式从可迭代对象中选择特定的元素。
"""
# 生成包含偶数平方数的元组序列
even_squares_tuple = tuple(x**2 for x in range(5) if x % 2 == 0)
print(even_squares_tuple)
运行效果:
python复制代码
"""
函数返回多个值:
在某些情况下,可能希望从函数中返回多个值作为元组,而元组推导式可以用于在函数中快速生成这样的元组。
"""
def get_coordinates():
x_values = [1, 2, 3]
y_values = [4, 5, 6]
return tuple((x, y) for x, y in zip(x_values, y_values))
coordinates = get_coordinates()
print(coordinates)
"""
转换数据格式:
当有一个可迭代对象,想要将其转换为字典形式时,字典推导式是一种便捷的方式。
例如,将元组列表转换为字典:
"""
tuple_list = [('a', 1), ('b', 2), ('c', 3)]
my_dict = {key: value for key, value in tuple_list}
print(tuple_list)
运行效果:
python复制代码
"""
过滤数据:
通过在字典推导式中添加条件表达式,可以过滤可迭代对象的元素,从而创建一个满足特定条件的字典。
例如,只选择某个范围内的元素
"""
original_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
filtered_dict = {key: value for key, value in original_dict.items() if value > 2}
print(filtered_dict)
运行效果:
python复制代码
"""
键或值的转换:
可以使用字典推导式来对字典的键或值进行某种转换。
例如,将字典的键和值交换:
"""
original_dict = {'a': 1, 'b': 2, 'c': 3}
swapped_dict = {value: key for key, value in original_dict.items()}
print(swapped_dict)
运行效果:
python复制代码
"""
处理嵌套结构:
当有一个嵌套的可迭代对象,想要将其展平为字典时,字典推导式也很有用。
例如,展平嵌套的字典:
"""
nested_dict = {'a': {'x': 1, 'y': 2}, 'b': {'x': 3, 'y': 4}}
flattened_dict = {outer_key: inner_value for outer_key, inner_dict in nested_dict.items() for inner_key, inner_value in inner_dict.items()}
print(flattened_dict)
"""
过滤数据:
可以使用集合推导式从一组数据中筛选出满足特定条件的元素。
例如,从一个列表中选择所有大于某个阈值的数字。
"""
numbers = [1, 5, 8, 10, 15, 20]
filtered_numbers = {x for x in numbers if x > 10}
print(filtered_numbers)
运行效果:
python复制代码
"""
映射转换:
使用集合推导式可以对数据进行转换,生成一个新的集合。例
如,将字符串列表转换为它们的长度集合。
"""
words = ["apple", "banana", "orange"]
word_lengths = {len(word) for word in words}
print(word_lengths)
运行效果:
python复制代码
"""
去重:
创建一个不包含重复元素的集合。这对于从列表或其他可迭代对象中移除重复项非常有用。
"""
numbers_with_duplicates = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = {x for x in numbers_with_duplicates}
print(unique_numbers)
运行效果:
python复制代码
"""
集合运算:
使用集合推导式进行集合运算,如并集、交集等。
例如,找到两个集合的交集。
"""
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
intersection = {x for x in set1 if x in set2}
print(intersection)
运行效果:
python复制代码
"""
条件化处理:
在集合推导式中,可以根据特定条件对元素进行处理。
例如,将列表中的奇数平方加倍。
"""
numbers = [1, 2, 3, 4, 5]
doubled_odd_squares = {x**2 * 2 for x in numbers if x % 2 != 0}
print(doubled_odd_squares)