Home  >  Article  >  Backend Development  >  Introduction to Python looping techniques (with code)

Introduction to Python looping techniques (with code)

不言
不言forward
2019-04-15 10:54:092340browse

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([&#39;tic&#39;, &#39;tac&#39;, &#39;toe&#39;]):
...     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 = [&#39;name&#39;, &#39;quest&#39;, &#39;favorite color&#39;]
>>> answers = [&#39;lancelot&#39;, &#39;the holy grail&#39;, &#39;blue&#39;]
>>> for q, a in zip(questions, answers):
...     print(&#39;What is your {0}?  It is {1}.&#39;.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 = [&#39;apple&#39;, &#39;orange&#39;, &#39;apple&#39;, &#39;pear&#39;, &#39;orange&#39;, &#39;banana&#39;]
>>> 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(&#39;NaN&#39;), 51.7, 55.3, 52.5, float(&#39;NaN&#39;), 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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete