当在字典中轮回时,用 items() 要领可将关键字和对应的值同时掏出
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.items(): ... print(k, v) ... gallahad the pure robin the brave
当在序列中轮回时,用 enumerate()
函数能够将索引位置和其对应的值同时掏出
>>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print(i, v) ... 0 tic 1 tac 2 toe
当同时在两个或更多序列中轮回时,能够用 zip()
函数将其内元素逐一婚配。
>>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip(questions, answers): ... print('What is your {0}? It is {1}.'.format(q, a)) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue.
当逆向轮回一个序列时,先正向定位序列,然后挪用 reversed()
函数
>>> for i in reversed(range(1, 10, 2)): ... print(i) ... 7 3
假如要按某个指定递次轮回一个序列,能够用 sorted()
函数,它能够在不修正原序列的基础上返回一个新的排好序的序列
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for f in sorted(set(basket)): ... print(f) ... apple banana orange pear
偶然可能会想在python轮回时修正列表内容,一般来说改成建立一个新列表是比较简单且平安的
>>> import math >>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8] >>> filtered_data = [] >>> for value in raw_data: ... if not math.isnan(value): ... filtered_data.append(value) ... >>> filtered_data [56.2, 51.7, 55.3, 52.5, 47.8]
【相干引荐:python教程】
以上就是Python轮回的技能引见(附代码)的细致内容,更多请关注ki4网别的相干文章!