列表生成
exp for iter_var in iterable
exp for iter_var in iterable if cond_expr
- 实例1:生成一个列表,列表中每个元素为1-10的2倍
list = [x*2 for x in range(1,11)]
print(list) //输出[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
- 实例2:生成一个列表,列表中每个元素为100内的偶数
list = [x for x in range(101) if x%2 == 0]
print(list) //输出[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]
- 实例3:生成一个列表,[[1, 0], [1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5]]
list = [[x,y] for x in range(1,3) for y in range(0,6)] //双重循环,列表中嵌套列表
print(list)