语法
- 普通
[expression for target in iterable]
- 带条件
[expression for target in iterable if condition]
- 嵌套
[expression for target1 in iterable1 if condition1
for target2 in iterable2 if condition2
...
for targetN in iterableN if conditionN]
实例
x = [1, 2, 3, 4, 5]
x = [i * 2 for i in x]
print(x)
y = [i for i in range(10)]
print(y)
matrix = [
[1, 2, 3],
[3, 5, 6],
[7, 8, 9]
]
col2 = [row[1] for row in matrix]
print(col2)
matrix = [
[1, 2, 3],
[3, 5, 6],
[7, 8, 9]
]
diag = [matrix[i][i] for i in range(len(matrix))]
print(diag)
diag2 = [matrix[i][len(matrix) - i - 1] for i in range(len(matrix))]
print(diag2)
a = [[0] * 3 for i in range(3)]
print(a)
a[1][1] = 5
print(a)
b = [i for i in range(20) if i % 2 == 0]
print(b)
words = ['Great', 'FishC', 'Brilliant', 'Excellent', 'Fantistic']
res = [word for word in words if word.startswith('F')]
print(res)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
flatten = [col for row in matrix for col in row ]
print(flatten)
等价于
flatten = []
for row in matrix:
for col in row:
flatten.append(col)
fulljoin = [x + y for x in '12345' for y in 'abcde']
print(fulljoin)
ans = [[x, y] for x in range(10) if x % 2 == 0 for y in range(10) if y % 3 == 0]
print(ans)
|