python 列表解析式 1,格式 2,单变量列表解析 3,多变量列表解析
1,格式 列表解析式 list comprehension 简单版本 [ expression for i in iterable ] [ expression for i in iterable if… for j in iterable if…] [ expression for i in iterable for j in iterable if…if… ] expression : 输出的结果 for i in iterable :需要迭代的对象 if… : 需要过滤的条件 2,单变量列表解析
lists=[]
for i in range(6):
lists.append(i)
print(lists)
print([i for i in range(6)])
[0, 1, 2, 3, 4, 5] [0, 1, 2, 3, 4, 5]
lists=[]
for i in range(6):
if i >=3:
lists.append(i)
print(lists)
print([i for i in range(6) if i>=3])
[3, 4, 5] [3, 4, 5] 3,多变量列表解析
lists=[]
for x in range(3):
for y in range(3):
lists.append([x,y])
print(lists)
print([[x,y] for x in range(3) for y in range(3)])
[[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]] [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
lists=[]
for x in range(3):
for y in range(3):
if y>=2:
lists.append([x,y])
print(lists)
print([[x,y] for x in range(3) for y in range(3) if y>=2])
print([[x,y] for x in range(3) for y in range(3) if y>=2 if x>=2])
[[0, 2], [1, 2], [2, 2]] [[0, 2], [1, 2], [2, 2]] [[2, 2]]
|