# Python基础教程5.6 简单推导

5.6 简单推导

>>> [x * x for x in range(10)]

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

>>> [x*x for x in range(10) if x 3 == 0] %

[0, 9, 36, 81]

>>> [(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)]

result = []

for x in range(3):

for y in range(3)

result.append((x, y))

>>> girls = ['alice', 'bernice', 'clarice']

>>> boys = ['chris', 'arnold', 'bob']

>>> [b+'+'+g for b in boys for g in girls if b[0] == g[0]]

['chris+clarice', 'arnold+alice', 'bob+bernice']

girls = ['alice', 'bernice', 'clarice']

boys = ['chris', 'arnold', 'bob']

letterGirls = {}

for girl in girls:

letterGirls.setdefault(girl[0], []).append(girl)

print([b+'+'+g for b in boys for g in letterGirls[b[0]]])

>>> squares = squared is {}".format(i, i**2) for i in range(10)}

>>> squares[8]

'8 squared is 64'

• 发表于:
• 原文链接https://kuaibao.qq.com/s/20180922G0G5V200?refer=cp_1026
• 腾讯「云+社区」是腾讯内容开放平台帐号（企鹅号）传播渠道之一，根据《腾讯内容开放平台服务协议》转载发布内容。
• 如有侵权，请联系 yunjia_community@tencent.com 删除。

2022-05-28

2022-05-28

2022-05-28

2022-05-28

2022-05-28

2022-05-28

2018-07-02

2018-05-08

2022-05-28

2022-05-28

2022-05-28

2022-05-28