https://docs.python.org/zh-cn/3/tutorial/datastructures.html#tut-loopidioms
When circulating in the dictionary, with a items()
can and a value corresponding to the keyword extraction method of simultaneously
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.items(): ... print(k, v) ... gallahad the pure robin the brave
When circulating in the sequence, with the enumerate()
possible position index and the corresponding value of the function taken at the same time
>>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print(i, v) ... 0 tic 1 tac 2 toe
When two or more while circulating in sequence, you can zip()
be one to one matched function within the element.
>>> 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.
When the reverse cycle of a sequence, a positive first targeting sequence, and then calls reversed()
the function
>>> for i in reversed(range(1, 10, 2)): ... print(i) ... 9 7 5 3 1
To carry out a given sequence of a cyclic sequence, can use sorted()
the function, it can not change a new return sorted sequence on the basis of the original sequence
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for f in sorted(set(basket)): ... print(f) ... apple banana orange pear
Sometimes may want to modify the list of contents at the time of the cycle, generally speaking instead create a new list is relatively simple and safe
>>> 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]