list 中使用循环创建新list

code

a = list(range(10))
print('a = ',a)

b= [x if x < 5 else 0 for x in a]
print('b = ', b)

output

a =  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b =  [0, 1, 2, 3, 4, 0, 0, 0, 0, 0]

code

a = [(x, y) for x in range(3) for y in range(4)]
print('a = ',a)

output

a =  [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]

你可能感兴趣的:(list 中使用循环创建新list)