列表推导式与生成器表达式
print([i for i in range(10)]) # 列表推导式 g = (i for i in range(10)) # 生成器表达式 print(g) # 打印的结果为生成器 print([i for i in g]) # 再次调用列表解析 >>>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <generator object <genexpr> at 0x0000006E50CBED58> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
列表推导式的补充:加上条件
ret = [i for i in range(30) if i % 3 == 0] print(ret) >>>[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
多重嵌套
>>> names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],
['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']]
>>> print([name for lst in names for name in lst if name.count('e') >= 2])
['Jefferson', 'Wesley', 'Steven', 'Jennifer']
字典推导式
>>> dic = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'} >>> {v1: k1 for k1, v1 in dic.items()} {'v1': 'k1', 'v2': 'k2', 'v3': 'k3'}
字典推导式值得注意的地方
>>> {key:value for key in "ABC" for value in range(1,10)} {'A': 9, 'B': 9, 'C': 9}
元组推导式
自带去重功能
squared = {x**2 for x in [1, -1, 2]} print(squared) # Output: set([1, 4]) >>>(1, 4)