python|python 简单推导式

1. []列表推导

print([x * x for x in range(10)])# 添加if print([x * x for x in range(10) if x % 3 == 0])# 更多的for print([(x, y) for x in range(3) for y in range(4)])# 例子 girls = ['alice', 'bernice', 'clarice'] boys = ['chris', 'arnold', 'bob'] letterGirls = {} for girl in girls: letterGirls.setdefault(girl[0], []).append(girl) print([boy + '+' + girl for boy in boys for girl in letterGirls[boy[0]]])

========================1========================= [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] [0, 9, 36, 81] [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)] ['chris+clarice', 'arnold+alice', 'bob+bernice']

2. {}字典推导
squares = { i: '{} squared is {}'.format(i, i**2) for i in range(10)} print(squares[8])

========================2========================= 8 squared is 64

3. ()创建生成器
generator = (x * x for x in range(10)) print(generator)

========================3========================= at 0x00000292DF34AA98>

    推荐阅读