列表推导式常用于生成简单有规律的列表,利用简洁的语法往往能达到令人意外的效果。
#列表推导式
list1 = [x for x in range(10)]
print(list1)
list1 = [x for x in range(10) if x % 2 == 0]
print(list1)
list1 = [x for x in range(10) if x % 2]
print(list1)
points = [(x,y) for x in range(1,5) for y in range (8,10)]
print(points)
m = [i for i in range(0,21)]
print(m)
n = [m[j:j + 3] for j in range (0,21)]
print(n)
n = [m[j:j + 3] for j in range (0,21,3)]
print(n)
结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8]
[1, 3, 5, 7, 9]
[(1, 8), (1, 9), (2, 8), (2, 9), (3, 8), (3, 9), (4, 8), (4, 9)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
[[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10, 11], [10, 11, 12], [11, 12, 13], [12, 13, 14], [13, 14, 15], [14, 15, 16], [15, 16, 17], [16, 17, 18], [17, 18, 19], [18, 19, 20], [19, 20], [20]]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19, 20]]