python 列表推导式
2020-12-13 03:32
标签:range let result pen div app color print nbsp result: python 列表推导式 标签:range let result pen div app color print nbsp 原文地址:https://www.cnblogs.com/lianghong881018/p/11078595.html>>> [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)]
girls = [‘alice‘, ‘bernice‘, ‘clarice‘, ‘aaaa‘]
boys = [‘chris‘, ‘arnold‘, ‘bob‘]
letterGirls = {}
for gril in girls:
letterGirls.setdefault(gril[0],[]).append(gril)
print(letterGirls)
print([b + ‘+‘ + g for b in boys for g in letterGirls[b[0]]])
{‘a‘: [‘alice‘, ‘aaaa‘], ‘b‘: [‘bernice‘], ‘c‘: [‘clarice‘]}
[‘chris+clarice‘, ‘arnold+alice‘, ‘arnold+aaaa‘, ‘bob+bernice‘]