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

Introduction to Python looping techniques (with code)

Apr 15, 2019 am 10:54 AM
python loop

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
Copy after login

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
Copy after login

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.
Copy after login

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
Copy after login

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
Copy after login

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]
Copy after login

[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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles