rabbits = ['Flopsy', 'Mopsy', 'Cottontail', 'Peter'] for rabbit in rabbits: print(rabbit)
运行结果:
1 2 3 4
Flopsy Mopsy Cottontail Peter
字符串迭代
1 2 3
word = 'cat' for letter in word: print(letter)
运行结果:
1 2 3
c a t
字典的迭代
1 2 3 4 5 6 7 8 9 10 11
accusation = {'room':'ballroom', 'weapon':'lead pipe', 'person':'Col. Mustard'} # 对字典的Key进行迭代 for card in accusation: print(card) for card in accusation.keys(): print(card) # 对字典的Value进行迭代 for item in accusation.items(): print(item) for card, contents in accusation.items(): print('Card', card, 'has the contents', contents)
运行结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
room weapon person room weapon person ballroom lead pipe Col. Mustard ('room', 'ballroom') ('weapon', 'lead pipe') ('person', 'Col. Mustard') Card room has the contents ballroom Card weapon has the contents lead pipe Card person has the contents Col. Mustard
for … else … 判断迭代是否正常结束,如果正常结束,执行else代码块,如果是break非正常结束,不执行else代码块
1 2 3 4 5 6 7 8 9
cheeses = ['aaa', 'bb', 'cc'] for cheese in cheeses: if cheese == 'aa': print('找到目标break跳出循环') break else: print('没找到') else: print('没有找到目标,执行了else的模块')
a_set = {number for number inrange(1, 6) if number % 3 == 1} print(a_set)
运行结果:
1
{1, 4}
生成器推导式
1 2 3 4 5 6 7 8 9
number_thing = (number for number inrange(1, 6)) # 返回的是一个生成器对象 print(type(number_thing)) # 方式1:直接对生成器对象进行迭代,注意生成器对象只能被迭代一次,迭代完成之后被擦除 for number in number_thing: print(number) # 方式2:将生成器对象转换成列表,然后再进行迭代 # number_list = list(number_thing) # print(number_list)