python 列表推导式
>>> [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]]])
result:
{'a': ['alice', 'aaaa'], 'b': ['bernice'], 'c': ['clarice']} ['chris+clarice', 'arnold+alice', 'arnold+aaaa', 'bob+bernice']