Python基础教程5章
##while 循环
name = ''
while not name.strip():
name = raw_input("input your name:\n")
print name
##for循环
words = ['today','is','a','good','day']
for word in words:
print word
##range函数
for i in range(1, 5):
print i
else:
print 'The for loop is over'
##字典的迭代
d = {'x':1,'y':2,'z':3}
for key in d:
print key,'is correspond to',d[key]
for key in d.keys():
print key
for value in d.values():
print value
for key,value in d.items():
print key,':',value
##并行迭代
names = ['annie','kevin','nic']
ages = ['21','22','23']
for i in range(len(names)):
print names[i],'is',ages[i],'years old'
##zip函数
for name,age in zip(names,ages):
print name,'is',age,'years old'
##索引
for index,name in enumerate(names):
if 'annie' in name:
names[index] = 'replaced'
print names
##列表推导式 找到名字首字母相同的男孩和女孩
girls = ['alice','benice','clarice']
boys = ['chris','arnold','bob']
print [b+'+'+g for b in boys for g in girls if b[0] == g[0]]
##更优方案
girls = ['alice','benice','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]]]