列表推到:
1. 列表的推导是为了更加简洁的去创建一个list
2. 列表推到格式
list = [exp for var in list ]
list = [exp for var in list if condition]
3. 示例
1.生成一个[1, 2, 3, 4, 5, 6, 7, 8, 9]序列
nums = list(item for item in range(1, 10)) print(nums)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
2. 求100以内能被3整除的数
nums = list(item for item in range(1, 40) if item % 3 == 0) print(nums)
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39]
4.实际应用
一个由男人列表和女人列表组成的嵌套列表,取出姓名中带有两个以上字母e的姓名,组成列表 names = [['Tom','Billy','Jefferson','Andrew','Wesley','Steven','Joe'], ['Alice','Jill','Ana','Wendy','Jennifer','Sherry','Eva']]
推到写法:
names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'], ['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']] nums = [name for lst in names for name in lst if name.count('e') >= 2] print(nums)
['Jefferson', 'Wesley', 'Steven', 'Jennifer']
展开写法:
result = [] for nums in names: for num in nums: result.append(num) for i in result: if i.count("e") >= 2: print(i)
Jefferson Wesley Steven Jennifer