推导式
1. 列表推导式,[x-express for x in iter]
-
利用其他的列表创建新的列表
#1. 基本语法 [x-express for x in lst] #2. 依次取出lst中的每个元素进行express运算,把结果放到新的列表中 [x * x for x in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] #3. 后面还可以加一个if部分,只取if后面运算为true的元素 >>> [x * x for x in range(10) if x % 3 == 0] [0, 9, 36, 81] >>> [x * x for x in range(10) if not x % 3] [0, 9, 36, 81] #4. for部分可以有多个,类似于嵌套循环 >>> [x for x in range(3) for y in range(3)] [0, 0, 0, 1, 1, 1, 2, 2, 2] >>> [(x, y) for x in range(3) for y in range(3)] [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] #5. 多个for部分是,可以在每个for后面跟if,也可以在最后加一个if >>> [(x, y) for x in range(3) if x == 1 for y in range(3)] [(1, 0), (1, 1), (1, 2)] >>> [(x, y) for x in range(3) for y in range(3) if x == 1] [(1, 0), (1, 1), (1, 2)]