Beginning Python: From Novice to Professional, Second Edition
时间:2010-09-04 来源:菜刀大侠
中文版p83页:
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]]])
输出结果:
>>>
['chris+clarice', 'arnold+alice', 'bob+bernice']
原理:
>>> girls = ['alice', 'bernice', 'clarice']
>>> letterGirls = {}
>>> for girl in girls:
letterGirls.setdefault(girl[0], []).append(girl)
>>> print letterGirls
{'a': ['alice'], 'c': ['clarice'], 'b': ['bernice']}
letterGirls.setdefault(girl[0], [])
'a':[]
letterGirls.setdefault(girl[0], []).append(girl)
'a':['alice']
如此便是个很好的方法。
p91:
斐波那契数列:
def fibs(num):
result = [0, 1]
for i in range(num-2):
result.append(result[-2] + result[-1])
return result
num = input('How many Fibonacci numbers do you want? ')
print fibs(num)