Python列表推导式使用举例

"""
列表推导式
功能说明:列表推导式可以利用 range 区间、元组、列表、字典和集合等数据类型,快速生成一个满足指定需求的列表。
语法:[表达式 for 迭代变量 in 可迭代对象 [if 条件表达式] ]
"""
list = [i + 1 for i in range(10)]
print(list)
"""
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
"""

list = [i * 2 for i in "hello"]
print(list)
"""
['hh', 'ee', 'll', 'll', 'oo']
"""

# 使用列表推导式创建多维列表
list = [[1] * 3 for i in range(3)]
print(list)
list[1][1] = 2
print(list)
"""
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
[[1, 1, 1], [1, 2, 1], [1, 1, 1]]
"""

# 带判断条件的列表推导式
list = [i + 1 for i in range(10) if i % 2 == 0]
print(list)
words = ["goods", "nice", "bad", "great"]
gList = [g for g in words if g.startswith("g")]
print(gList)
"""
[1, 3, 5, 7, 9]
['goods', 'great']
[1, 2, 3, 2, 4, 6, 3, 6, 9]
"""

# 多层列表推导式
m = [(i + 1) * (n + 1) for i in range(3) for n in range(3)]
print(m)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list = [col for row in matrix for col in row]
print(list)
"""
[1, 2, 3, 2, 4, 6, 3, 6, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
"""

# 多层多条件列表表达式
list = [[x, y] for x in range(5) if x % 2 == 0 for y in range(5) if y % 3 == 0]
print(list)
"""
[[0, 0], [0, 3], [2, 0], [2, 3], [4, 0], [4, 3]]
"""

 

posted @ 2023-01-07 15:30  星瑞  阅读(94)  评论(0编辑  收藏  举报