This article brings you an introduction to Python looping skills (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
When looping in the dictionary, use the items() method to take out the keywords and corresponding values at the same time
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.items(): ... print(k, v) ... gallahad the pure robin the brave
When looping in the sequence, use <span class="pre">enumerate()</span>
The function can take out the index position and its corresponding value at the same time
>>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print(i, v) ... 0 tic 1 tac 2 toe
When looping in two or more sequences at the same time, you can use <span class="pre">zip()</span>
The function matches the elements inside it one by one.
>>> 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 looping a sequence in the reverse direction, first position the sequence in the forward direction, and then call the <span class="pre">reversed()</span>
function
>>> for i in reversed(range(1, 10, 2)): ... print(i) ... 7 3
If you want to press a certain To cycle through a sequence in a specified order, you can use the <span class="pre">sorted()</span>
function, which can return a new sorted sequence without changing the original sequence
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for f in sorted(set(basket)): ... print(f) ... apple banana orange pear
Sometimes you may want to modify the contents of the list while python is looping. Generally speaking, it is simpler and safer to create a new list instead
>>> 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]
[Related recommendations: python tutorial 】
The above is the detailed content of Introduction to Python looping techniques (with code). For more information, please follow other related articles on the PHP Chinese website!