Home Backend Development Python Tutorial Python中for循环详解

Python中for循环详解

Jun 16, 2016 am 08:45 AM
for loop python

与其它大多数语言一样,Python 也拥有 for 循环。你到现在还未曾看到它们的唯一原因就是,Python 在其它太多的方面表现出色,通常你不需要它们。

其它大多数语言没有像 Python 一样的强大的 list 数据类型,所以你需要亲自做很多事情,指定开始,结束和步长,来定义一定范围的整数或字符或其它可重复的实体。但是在 Python 中,for 循环简单地在一个列表上循环,与 list 解析的工作方式相同。

1. for  循环介绍

复制代码 代码如下:

>>> li = ['a', 'b', 'e']
>>> for s in li:         (1)
...     print s          (2)
a

e
>>> print "\n".join(li)  (3)
a

e

(1)  for 循环的语法同 list 解析相似。li 是一个 list,而 s 将从第一个元素开始依次接收每个元素的值。
(2)  像 if 语句或其它任意缩进块,for 循环可以包含任意数目的代码行。
(3)  这就是你以前没看到过 for 循环的原因:至今我们都不需要它。太令人吃惊了,当你想要的只是一个 join 或是 list 解析时,在其它语言中常常需要使用 for 循环。

要做一个 “通常的” (Visual Basic 标准的) 计数 for 循环也非常简单。

2. 简单计数

复制代码 代码如下:

>>> for i in range(5):             (1)
...     print i
0
1
2
3
4
>>> li = ['a', 'b', 'c', 'd', 'e']
>>> for i in range(len(li)):       (2)
- 104 -Dive Into Python http://diveintopython.org/
...     print li[i]
a

c
d
e

(1)  range 生成一个整数的 list,通过它来控制循环。我知道它看上去有些奇怪,但是它对计数循环偶尔 (我只是说偶尔) 会有用 。
(2)  我们从来没这么用过。这是 Visual Basic 的思维风格。摆脱它吧。正确遍历 list 的方法是前面的例子所展示的。

for 循环不仅仅用于简单计数。它们可以遍历任何类型的东西。下面的例子是一个用 for 循环遍历 dictionary 的例子。

3. 遍历  dictionary

复制代码 代码如下:

>>> import os
>>> for k, v in os.environ.items():      (1) (2)
...     print "%s=%s" % (k, v)
USERPROFILE=C:\Documents and Settings\mpilgrim
OS=Windows_NT
COMPUTERNAME=MPILGRIM
USERNAME=mpilgrim
[...略...]
>>> print "\n".join(["%s=%s" % (k, v)
...     for k, v in os.environ.items()]) (3)
USERPROFILE=C:\Documents and Settings\mpilgrim
OS=Windows_NT
COMPUTERNAME=MPILGRIM
USERNAME=mpilgrim
[...略...]

(1)  os.environ 是在你的系统上所定义的环境变量的 dictionary。在 Windows 下,这些变量是可以从 MS-DOS 访问的用户和系统变量。在 UNIX 下,它们是在你的 shell 启动脚本中所 export (输出) 的变量。在 Mac OS 中,没有环境变量的概念,所以这个 dictionary 为空。
(2)  os.environ.items() 返回一个 tuple 的 list:[(key1, value1), (key2, value2), ...]。for 循环对这个 list 进行遍历。第一轮,它将 key1 赋给 k ,value1 赋给 v,所以 k = USERPROFILE,v = C:\Documents and Settings\mpilgrim。第二轮,k 得到第二个键字 OS,v 得到相应的值 Windows_NT。
(3)  使用多变量赋值和 list 解析,你可以使用单行语句来替换整个 for 循环。在实际的编码中是否这样做只是个人风格问题;我喜欢它是因为,将一个dictionary 映射到一个 list,然后将 list 合并成一个字符串,这一过程显得很清晰。其它的程序员宁愿将其写成一个 for 循环。请注意在两种情况下输出是一样的,然而这一版本稍微快一些,因为它只有一条 print 语句而不是许多。

现在我们来看看在 第 5 章介绍的样例程序 fileinfo.py 中 MP3FileInfo 的 for 循环 。

复制代码 代码如下:

    tagDataMap = {"title"   : (  3,  33, stripnulls),
                  "artist"  : ( 33,  63, stripnulls),
                  "album"   : ( 63,  93, stripnulls),
                  "year"    : ( 93,  97, stripnulls),
                  "comment" : ( 97, 126, stripnulls),
                  "genre"   : (127, 128, ord)}                               (1)
    .
    .
    .
            if tagdata[:3] == "TAG":
                for tag, (start, end, parseFunc) in self.tagDataMap.items(): (2)
                    self[tag] = parseFunc(tagdata[start:end])                (3)

(1)  tagDataMap 是一个类属性,它定义了我们正在一个 MP3 文件中搜索的标记。标记存储为定长字段,只要我们读出文件最后 128 个字节,那么第 3 到 32 字节总是歌曲的名字,33-62 总是歌手的名字,63-92 为专辑的名字,等等。请注意 tagDataMap 是一个 tuple 的 dictionary,每个 tuple 包含两个整数和一个函数引用。
(2)  这个看上去复杂一些,但其实并非如此。这里的 for 变量结构与 items 所返回的 list 的元素的结构相匹配。记住,items 返回一个形如 (key, value) 的 tuple 的 list。list 第一个元素是 ("title", (3, 33, )),所以循环的第一轮,tag 为 "title",start 为 3,end 为 33,parseFunc 为函数 stripnulls。
(3)  现在我们已经从一个单个的 MP3 标记中提取出了所有的参数,将标记数据保存起来挺容易。我们从 start 到 end 对 tagdata 进行分片,从而得到这个标记的实际数据,调用 parseFunc 对数据进行后续的处理,接着将
parseFunc 的返回值作为值赋值给伪字典 self 中的键字 tag。在遍历完 tagDataMap 中所有元素之后,self 拥有了所有标记的值,你知道看上去是什么样。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Google AI announces Gemini 1.5 Pro and Gemma 2 for developers Google AI announces Gemini 1.5 Pro and Gemma 2 for developers Jul 01, 2024 am 07:22 AM

Google AI has started to provide developers with access to extended context windows and cost-saving features, starting with the Gemini 1.5 Pro large language model (LLM). Previously available through a waitlist, the full 2 million token context windo

How to download deepseek Xiaomi How to download deepseek Xiaomi Feb 19, 2025 pm 05:27 PM

How to download DeepSeek Xiaomi? Search for "DeepSeek" in the Xiaomi App Store. If it is not found, continue to step 2. Identify your needs (search files, data analysis), and find the corresponding tools (such as file managers, data analysis software) that include DeepSeek functions.

How do you ask him deepseek How do you ask him deepseek Feb 19, 2025 pm 04:42 PM

The key to using DeepSeek effectively is to ask questions clearly: express the questions directly and specifically. Provide specific details and background information. For complex inquiries, multiple angles and refute opinions are included. Focus on specific aspects, such as performance bottlenecks in code. Keep a critical thinking about the answers you get and make judgments based on your expertise.

What software is NET40? What software is NET40? May 10, 2024 am 01:12 AM

.NET 4.0 is Microsoft's software development platform that provides a framework and toolset for building a variety of applications, including web, desktop, and mobile applications. Its features include: Parallel Programming Library (TPL) Parallel LINQ (PLINQ) Dynamic Language Runtime (DLR) Silverlight 5Windows Communication Foundation (WCF) 4.0. Benefits include: Performance improvements Code reusability Cross-platform support Developer-friendliness Security.

How to search deepseek How to search deepseek Feb 19, 2025 pm 05:18 PM

Just use the search function that comes with DeepSeek. Its powerful semantic analysis algorithm can accurately understand the search intention and provide relevant information. However, for searches that are unpopular, latest information or problems that need to be considered, it is necessary to adjust keywords or use more specific descriptions, combine them with other real-time information sources, and understand that DeepSeek is just a tool that requires active, clear and refined search strategies.

How to program deepseek How to program deepseek Feb 19, 2025 pm 05:36 PM

DeepSeek is not a programming language, but a deep search concept. Implementing DeepSeek requires selection based on existing languages. For different application scenarios, it is necessary to choose the appropriate language and algorithms, and combine machine learning technology. Code quality, maintainability, and testing are crucial. Only by choosing the right programming language, algorithms and tools according to your needs and writing high-quality code can DeepSeek be successfully implemented.

How to use deepseek to settle accounts How to use deepseek to settle accounts Feb 19, 2025 pm 04:36 PM

Question: Is DeepSeek available for accounting? Answer: No, it is a data mining and analysis tool that can be used to analyze financial data, but it does not have the accounting record and report generation functions of accounting software. Using DeepSeek to analyze financial data requires writing code to process data with knowledge of data structures, algorithms, and DeepSeek APIs to consider potential problems (e.g. programming knowledge, learning curves, data quality)

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

See all articles