python列表
列表推导式
例1
1 [ i*i for i in range(10) ]
打印如下:
1 >>> [i*i for i in range(10)] 2 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
相当于:
1 a=[] 2 for i in range(10): 3 b=i*i 4 a.append(b)
例2
1 >>> list1 = [(x, y) for x in range(10) for y in range(10) if x%2==0 if y%2!=0]
相当于
1 list1 = [] 2 for x in range(10): 3 for y in range(10): 4 if x%2 == 0: 5 if y%2 != 0: 6 list1.append((x, y))