博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python“ for”循环(定迭代)
阅读量:2525 次
发布时间:2019-05-11

本文共 23817 字,大约阅读时间需要 79 分钟。

This tutorial will show you how to perform definite iteration with a Python for loop.

本教程将向您展示如何使用Python for循环执行确定的迭代

In the in this introductory series, you learned the following:

在本入门系列的中,您了解了以下内容:

  • Repetitive execution of the same block of code over and over is referred to as iteration.
  • There are two types of iteration:
    • Definite iteration, in which the number of repetitions is specified explicitly in advance
    • Indefinite iteration, in which the code block executes until some condition is met
  • In Python, indefinite iteration is performed with a while loop.
  • 一遍又一遍地重复执行同一代码块称为迭代
  • 有两种类型的迭代:
    • 确定迭代,其中重复数是预先明确指定的
    • 不定迭代,其中代码块执行直到满足某些条件
  • 在Python中,使用while循环执行不确定的迭代。

Here’s what you’ll cover in this tutorial:

这是本教程将介绍的内容:

  • You’ll start with a comparison of some different paradigms used by programming languages to implement definite iteration.

  • Then you will learn about iterables and iterators, two concepts that form the basis of definite iteration in Python.

  • Finally, you’ll tie it all together and learn about Python’s for loops.

  • 您将首先比较编程语言用于实现确定迭代的一些不同范例。

  • 然后,您将学习iterablesiterators ,这两个概念构成了Python中确定迭代的基础。

  • 最后,将所有内容捆绑在一起,并了解Python的for循环。

Free Bonus: that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.

免费红利: 通过简单的示例向您展示了Python的最佳实践,您可以立即应用这些示例编写更精美的Pythonic代码。

编程中的确定迭代概述 (A Survey of Definite Iteration in Programming)

Definite iteration loops are frequently referred to as for loops because for is the keyword that is used to introduce them in nearly all programming languages, including Python.

确定迭代循环通常称为for循环,因为for是几乎所有编程语言(包括Python)中用来引入它们的关键字。

Historically, programming languages have offered a few assorted flavors of for loop. These are briefly described in the following sections.

从历史上看,编程语言提供了多种for循环样式。 以下各节简要介绍了这些内容。

数值范围循环 (Numeric Range Loop)

The most basic for loop is a simple numeric range statement with start and end values. The exact format varies depending on the language but typically looks something like this:

最基本的for循环是带有起始值和结束值的简单数字范围语句。 确切的格式取决于语言,但通常看起来像这样:

forfor    ii    ==    11    toto    1010         << looploop    bodybody >>

Here, the body of the loop is executed ten times. The variable i assumes the value 1 on the first iteration, 2 on the second, and so on. This sort of for loop is used in the languages BASIC, Algol, and Pascal.

在此,循环主体执行十次。 可变i假定值1上的第一次迭代, 2在第二,等等。 这种for循环在BASIC,Algol和Pascal语言中使用。

三表达循环 (Three-Expression Loop)

Another form of for loop popularized by the C programming language contains three parts:

C编程语言流行的另一种形式的for循环包含三个部分:

  • An initialization
  • An expression specifying an ending condition
  • An action to be performed at the end of each iteration.
  • 初始化
  • 指定结束条件的表达式
  • 在每次迭代结束时要执行的动作。

This type of has the following form:

这种类型具有以下形式:

Technical Note: In the C programming language, i++ increments the variable i. It is roughly equivalent to i += 1 in Python.

技术说明:在C编程语言中, i++将变量i递增。 它大致等于Python中的i += 1

This loop is interpreted as follows:

此循环的解释如下:

  • Initialize i to 1.
  • Continue looping as long as i <= 10.
  • Increment i by 1 after each loop iteration.
  • i初始化为1
  • 只要i <= 10继续循环。
  • 每次循环迭代后,将i递增1

Three-expression for loops are popular because the expressions specified for the three parts can be nearly anything, so this has quite a bit more flexibility than the simpler numeric range form shown above. These for loops are also featured in the C++, Java, PHP, and Perl languages.

三种形式的for循环很受欢迎,因为为这三个部分指定的表达式几乎可以是任何东西,因此与上面显示的简单数字范围形式相比,它具有更大的灵活性。 这些for循环在C ++,Java,PHP和Perl语言中也具有特色。

基于集合或基于迭代器的循环 (Collection-Based or Iterator-Based Loop)

This type of loop iterates over a collection of objects, rather than specifying numeric values or conditions:

这种类型的循环遍历对象的集合,而不是指定数值或条件:

for for i i in in << collectioncollection >    >    << loop loop bodybody >>

Each time through the loop, the variable i takes on the value of the next object in <collection>. This type of for loop is arguably the most generalized and abstract. Perl and PHP also support this type of loop, but it is introduced by the keyword foreach instead of for.

每次循环时,变量i都会使用<collection>下一个对象的值。 这种类型的for循环可以说是最概括和抽象的。 Perl和PHP也支持这种类型的循环,但是它是由关键字foreach而不是for引入的。

Further Reading: See the Wikipedia page for an in-depth look at the implementation of definite iteration across programming languages.

进一步阅读:请参阅 Wikipedia页面,以深入了解跨编程语言的确定迭代的实现。

Python for循环 (The Python for Loop)

Of the loop types listed above, Python only implements the last: collection-based iteration. At first blush, that may seem like a raw deal, but rest assured that Python’s implementation of definite iteration is so versatile that you won’t end up feeling cheated!

在上面列出的循环类型中,Python仅实现最后一个:基于集合的迭代。 乍一看,这看起来似乎很原始,但是请放心,Python的确定迭代的实现是如此通用,以至于您最终不会被欺骗!

Shortly, you’ll dig into the guts of Python’s for loop in detail. But for now, let’s start with a quick prototype and example, just to get acquainted.

很快,您将详细研究Python的for循环的精髓。 但是现在,让我们从快速的原型和示例开始,以便结识。

Python’s for loop looks like this:

Python的for循环如下所示:

<iterable> is a collection of objects—for example, a list or tuple. The <statement(s)> in the loop body are denoted by indentation, as with all Python control structures, and are executed once for each item in <iterable>. The loop variable <var> takes on the value of the next element in <iterable> each time through the loop.

<iterable>是对象的集合,例如列表或元组。 与所有Python控件结构一样,循环主体中的<statement(s)>由缩进表示,并且对<iterable>每个项目执行一次。 每次循环时,循环变量<var>都会采用<iterable>下一个元素的值。

Here is a representative example:

这是一个代表性的例子:

>>>
>>> a = ['foo', 'bar', 'baz']>>> for i in a:...     print(i)...foobarbaz
>>>

In this example, <iterable> is the list a, and <var> is the variable i. Each time through the loop, i takes on a successive item in a, so print() displays the values 'foo', 'bar', and 'baz', respectively. A for loop like this is the Pythonic way to process the items in an iterable.

在此示例中, <iterable>是列表a ,而<var>是变量i 。 通过每一次循环中, i呈现在相继的项a ,因此print()显示的值'foo''bar' ,和'baz'分别。 像这样的for循环是Python方式来迭代处理项目。

But what exactly is an iterable? Before examining for loops further, it will be beneficial to delve more deeply into what iterables are in Python.

但是到底什么是可迭代的呢? 审前for循环此外,将有利于更深入地钻研什么iterables在Python。

可迭代 (Iterables)

In Python, iterable means an object can be used in iteration. The term is used as:

在Python中, 可迭代意味着对象可以在迭代中使用。 该术语用作:

  • An adjective: An object may be described as iterable.
  • A noun: An object may be characterized as an iterable.
  • 形容词:一个对象可能被描述为可迭代的。
  • 名词:一个对象可以被描述为可迭代的。

If an object is iterable, it can be passed to the built-in Python function iter(), which returns something called an iterator. Yes, the terminology gets a bit repetitive. Hang in there. It all works out in the end.

如果对象是可迭代的,则可以将其传递给内置的Python函数iter() ,该函数返回称为iterator的内容 。 是的,术语有点重复。 等一下 一切最终都解决了。

Each of the objects in the following example is an iterable and returns some type of iterator when passed to iter():

以下示例中的每个对象都是可迭代的,并在传递给iter()时返回某种类型的迭代器:

>>>
>>> iter('foobar')                             # String
>>> iter(['foo', 'bar', 'baz']) # List
>>> iter(('foo', 'bar', 'baz')) # Tuple
>>> iter({
'foo', 'bar', 'baz'}) # Set
>>> iter({
'foo': 1, 'bar': 2, 'baz': 3}) # Dict
>>>

These object types, on the other hand, aren’t iterable:

另一方面,这些对象类型是不可迭代的:

>>>
>>> iter(42)                                   # IntegerTraceback (most recent call last):  File "
", line 1, in
iter(42)TypeError: 'int' object is not iterable>>> iter(3.1) # FloatTraceback (most recent call last): File "
", line 1, in
iter(3.1)TypeError: 'float' object is not iterable>>> iter(len) # Built-in functionTraceback (most recent call last): File "
", line 1, in
iter(len)TypeError: 'builtin_function_or_method' object is not iterable
>>>

All the data types you have encountered so far that are collection or container types are iterable. These include the , , , , , and types.

到目前为止,您遇到的所有数据类型都是集合或容器类型,都是可迭代的。 这些类型包括 , , , , 和类型。

But these are by no means the only types that you can iterate over. Many objects that are built into Python or defined in modules are designed to be iterable. For example, open files in Python are iterable. As you will see soon in the tutorial on file I/O, iterating over an open file object reads data from the file.

但是,这些绝不是您可以迭代的唯一类型。 Python中内置的或模块中定义的许多对象被设计为可迭代的。 例如,在Python中打开文件是可迭代的。 正如您将在有关文件I / O的教程中很快看到的那样,对打开的文件对象进行迭代会从文件中读取数据。

In fact, almost any object in Python can be made iterable. Even user-defined objects can be designed in such a way that they can be iterated over. (You will find out how that is done in the upcoming article on object-oriented programming.)

实际上,Python中几乎所有对象都可以变得可迭代。 即使是用户定义的对象,也可以以可以迭代的方式进行设计。 (您将在下一篇有关面向对象编程的文章中找到如何完成此操作的。)

迭代器 (Iterators)

Okay, now you know what it means for an object to be iterable, and you know how to use iter() to obtain an iterator from it. Once you’ve got an iterator, what can you do with it?

好的,现在您知道对象可迭代的含义,并且知道如何使用iter()从对象中获取迭代器。 一旦有了迭代器,该怎么办?

An iterator is essentially a value producer that yields successive values from its associated iterable object. The built-in function next() is used to obtain the next value from in iterator.

迭代器本质上是一个值生成器,它从其关联的可迭代对象产生连续值。 内置函数next()用于从迭代器中获取下一个值。

Here is an example using the same list as above:

这是使用与上面相同的列表的示例:

>>>
>>> a = ['foo', 'bar', 'baz']>>> itr = iter(a)>>> itr
>>> next(itr)'foo'>>> next(itr)'bar'>>> next(itr)'baz'
>>>

In this example, a is an iterable list and itr is the associated iterator, obtained with iter(). Each next(itr) call obtains the next value from itr.

在此示例中, a是一个可迭代的列表,并且itr是使用iter()获得的关联迭代器。 每个next(itr)调用都从itr获得下一个值。

Notice how an iterator retains its state internally. It knows which values have been obtained already, so when you call next(), it knows what value to return next.

注意迭代器如何在内部保留其状态。 它知道已经获得了哪些值,因此当您调用next() ,它知道接下来要返回什么值。

What happens when the iterator runs out of values? Let’s make one more next() call on the iterator above:

当迭代器的值用完时会发生什么? 让我们在上面的迭代器上再进行一次next()调用:

>>>
>>> next(itr)Traceback (most recent call last):  File "
", line 1, in
next(itr)StopIteration
>>>

If all the values from an iterator have been returned already, a subsequent next() call raises a StopIteration exception. Any further attempts to obtain values from the iterator will fail.

如果已经返回了迭代器的所有值,则后续的next()调用将引发StopIteration异常。 从迭代器获取值的任何进一步尝试都将失败。

You can only obtain values from an iterator in one direction. You can’t go backward. There is no prev() function. But you can define two independent iterators on the same iterable object:

您只能从一个方向的迭代器获取值。 你不能后退。 没有prev()函数。 但是您可以在同一个可迭代对象上定义两个独立的迭代器:

>>>
>>> a['foo', 'bar', 'baz']>>> itr1 = iter(a)>>> itr2 = iter(a)>>> next(itr1)'foo'>>> next(itr1)'bar'>>> next(itr1)'baz'>>> next(itr2)'foo'
>>>

Even when iterator itr1 is already at the end of the list, itr2 is still at the beginning. Each iterator maintains its own internal state, independent of the other.

即使迭代器itr1已经在列表的末尾, itr2仍然在列表的开始。 每个迭代器都维护自己的内部状态,彼此独立。

If you want to grab all the values from an iterator at once, you can use the built-in list() function. Among other possible uses, list() takes an iterator as its argument, and returns a list consisting of all the values that the iterator yielded:

如果要一次从迭代器中获取所有值,则可以使用内置的list()函数。 在其他可能的用法中, list()将迭代器作为其参数,并返回一个由迭代器产生的所有值组成的列表:

>>>
>>> a = ['foo', 'bar', 'baz']>>> itr = iter(a)>>> list(itr)['foo', 'bar', 'baz']
>>>

Similarly, the built-in tuple() and set() functions return a tuple and a set, respectively, from all the values an iterator yields:

同样,内置的tuple()set()函数从迭代器产生的所有值中分别返回一个元组和一个集合:

>>>
>>> a = ['foo', 'bar', 'baz']>>> itr = iter(a)>>> tuple(itr)('foo', 'bar', 'baz')>>> itr = iter(a)>>> set(itr){'baz', 'foo', 'bar'}
>>>

It isn’t necessarily advised to make a habit of this. Part of the elegance of iterators is that they are “lazy.” That means that when you create an iterator, it doesn’t generate all the items it can yield just then. It waits until you ask for them with next(). Items are not created until they are requested.

不一定要养成这种习惯。 迭代器的部分优雅之处在于它们是“懒惰的”。 这意味着,当您创建迭代器时,它不会生成当时可以产生的所有项。 它一直等到您通过next()要求它们。 除非请求,否则不会创建项目。

When you use list(), tuple(), or the like, you are forcing the iterator to generate all its values at once, so they can all be returned. If the total number of objects the iterator returns is very large, that may take a long time.

当使用list()tuple()或类似方法时,您将强制迭代器立即生成其所有值,以便可以将它们全部返回。 如果迭代器返回的对象总数很大,则可能需要很长时间。

In fact, it is possible to create an iterator in Python that returns an endless series of objects. (You will learn how to do this in upcoming tutorials on generator functions and itertools.) If you try to grab all the values at once from an endless iterator, the program will .

实际上,可以在Python中创建一个迭代器,该迭代器返回一系列无穷的对象。 (您将在即将到来的有关生成器函数和itertools教程中学习如何执行此操作。)如果尝试一次从一个无限的迭代器中获取所有值,则该程序将 。

Python for Loop的勇气 (The Guts of the Python for Loop)

You now have been introduced to all the concepts you need to fully understand how Python’s for loop works. Before proceeding, let’s review the relevant terms:

现在,向您介绍了充分了解Python的for循环工作原理所需的所有概念。 在继续之前,让我们回顾一下相关条款:

Term 术语 Meaning 含义
Iteration迭代 The process of looping through the objects or items in a collection 遍历集合中的对象或项目的过程
Iterable可迭代的 An object (or the adjective used to describe an object) that can be iterated over 可以迭代的对象(或用于描述对象的形容词)
Iterator迭代器 The object that produces successive items or values from its associated iterable 从其关联的可迭代对象产生连续项或值的对象
iter()iter() The built-in function used to obtain an iterator from an iterable 用于从可迭代对象获得迭代器的内置函数

Now, consider again the simple for loop presented at the start of this tutorial:

现在,再次考虑本教程开始时介绍的简单for循环:

>>>
>>> a = ['foo', 'bar', 'baz']>>> for i in a:...     print(i)...foobarbaz
>>>

This loop can be described entirely in terms of the concepts you have just learned about. To carry out the iteration this for loop describes, Python does the following:

该循环可以完全按照您刚刚了解的概念来描述。 为了执行此for循环描述的迭代,Python执行以下操作:

  • Calls iter() to obtain an iterator for a
  • Calls next() repeatedly to obtain each item from the iterator in turn
  • Terminates the loop when next() raises the StopIteration exception
  • 调用iter()以获得一个迭代a
  • 重复调用next()依次从迭代器中获取每个项目
  • next()引发StopIteration异常时终止循环

The loop body is executed once for each item next() returns, with loop variable i set to the given item for each iteration.

对于每个项next()返回,循环体都会执行一次,循环变量i设置为每次迭代的给定项。

This sequence of events is summarized in the following diagram:

下图中总结了事件的顺序:

Python for loop diagram
Schematic Diagram of a Python for Loop
Python for Loop的示意图

Perhaps this seems like a lot of unnecessary monkey business, but the benefit is substantial. Python treats looping over all iterables in exactly this way, and in Python, iterables and iterators abound:

也许这似乎是很多不必要的猴子生意,但好处却是可观的。 Python完全以这种方式对待遍历所有可迭代对象,在Python中,可迭代对象和迭代器比比皆是:

  • Many built-in and library objects are iterable.

  • There is a Standard Library module called itertools containing many functions that return iterables.

  • User-defined objects created with Python’s object-oriented capability can be made to be iterable.

  • Python features a construct called a generator that allows you to create your own iterator in a simple, straightforward way.

  • 许多内置对象和库对象都是可迭代的。

  • 有一个称为itertools的标准库模块,其中包含许多返回可迭代对象的函数。

  • 使用Python的面向对象功能创建的用户定义对象可以使其可迭代。

  • Python具有称为生成器的构造,可让您以简单,直接的方式创建自己的迭代器。

You will discover more about all the above throughout this series. They can all be the target of a for loop, and the syntax is the same across the board. It’s elegant in its simplicity and eminently versatile.

在本系列中,您将发现有关以上所有内容的更多信息。 它们都可以成为for循环的目标,并且语法完全相同。 它以其简单而优雅而出众。

遍历字典 (Iterating Through a Dictionary)

You saw earlier that an iterator can be obtained from a dictionary with iter(), so you know dictionaries must be iterable. What happens when you loop through a dictionary? Let’s see:

您之前已经看到可以使用iter()从字典中获得迭代器,因此您知道字典必须是可迭代的。 当您浏览字典时会发生什么? 让我们来看看:

>>>
>>> d = {
'foo': 1, 'bar': 2, 'baz': 3}>>> for k in d:... print(k)...foobarbaz
>>>

As you can see, when a for loop iterates through a dictionary, the loop variable is assigned to the dictionary’s keys.

如您所见,当for循环遍历字典时,循环变量将分配给字典的键。

To access the dictionary values within the loop, you can make a dictionary reference using the key as usual:

要在循环中访问字典值,您可以像往常一样使用键来引用字典:

>>>
>>> for k in d:...     print(d[k])...123
>>>

You can also iterate through a dictionary’s values directly by using .values():

您还可以使用.values()直接遍历字典的值:

>>>
>>> for v in d.values():...     print(v)...123
>>>

In fact, you can iterate through both the keys and values of a dictionary simultaneously. That is because the loop variable of a for loop isn’t limited to just a single variable. It can also be a tuple, in which case the assignments are made from the items in the iterable using packing and unpacking, just as with an assignment statement:

实际上,您可以同时遍历字典的键和值。 这是因为for循环的循环变量不仅限于单个变量。 它也可以是一个元组,在这种情况下,分配是使用打包和拆包从可迭代项中进行的,就像分配语句一样:

>>>
>>> i, j = (1, 2)>>> print(i, j)1 2>>> for i, j in [(1, 2), (3, 4), (5, 6)]:...     print(i, j)...1 23 45 6
>>>

As noted in the tutorial on Python , the dictionary method .items() effectively returns a list of key/value pairs as tuples:

如有关Python 的教程所述,字典方法.items()有效地将键/值对的列表作为元组返回:

>>>
>>> d = {
'foo': 1, 'bar': 2, 'baz': 3}>>> d.items()dict_items([('foo', 1), ('bar', 2), ('baz', 3)])
>>>

Thus, the Pythonic way to iterate through a dictionary accessing both the keys and values looks like this:

因此,Python遍历字典访问键和值的方式如下所示:

>>>
>>> d = {
'foo': 1, 'bar': 2, 'baz': 3}>>> for k, v in d.items():... print('k =', k, ', v =', v)...k = foo , v = 1k = bar , v = 2k = baz , v = 3
>>>

range()函数 (The range() Function)

In the first section of this tutorial, you saw a type of for loop called a , in which starting and ending numeric values are specified. Although this form of for loop isn’t directly built into Python, it is easily arrived at.

在本教程的第一部分中,您看到了一种称为的for ,其中指定了起始和结束数值。 尽管这种形式的for循环不是直接构建在Python中,但很容易实现。

For example, if you wanted to iterate through the values from 0 to 4, you could simply do this:

例如,如果您要遍历04的值,则只需执行以下操作:

>>>
>>> for n in (0, 1, 2, 3, 4):...     print(n)...01234
>>>

This solution isn’t too bad when there are just a few numbers. But if the number range were much larger, it would become tedious pretty quickly.

当只有几个数字时,此解决方案还不错。 但是,如果数字范围大得多,它将很快变得乏味。

Happily, Python provides a better option—the built-in range() function, which returns an iterable that yields a sequence of integers.

令人高兴的是,Python提供了一个更好的选项-内置range()函数,该函数返回一个可迭代的整数序列。

range(<end>) returns an iterable that yields integers starting with 0, up to but not including <end>:

range(<end>)返回一个可迭代的对象,该对象生成以0开头(但不包括<end> range(<end>)的整数:

>>>
>>> x = range(5)>>> xrange(0, 5)>>> type(x)
>>>

Note that range() returns an object of class range, not a list or tuple of the values. Because a range object is an iterable, you can obtain the values by iterating over them with a for loop:

请注意, range()返回的是class range的对象,而不是值的列表或元组。 由于range对象是可迭代的,因此可以通过使用for循环遍历它们来获取值:

>>>
>>> for n in x:...     print(n)...01234
>>>

You could also snag all the values at once with list() or tuple(). In a REPL session, that can be a convenient way to quickly display what the values are:

您还可以使用list()tuple()一次捕获所有值。 在REPL会话中,这可以是一种快速显示值的便捷方法:

>>>
>>> list(x)[0, 1, 2, 3, 4]>>> tuple(x)(0, 1, 2, 3, 4)
>>>

However, when range() is used in code that is part of a larger application, it is typically considered poor practice to use list() or tuple() in this way. Like iterators, range objects are lazy—the values in the specified range are not generated until they are requested. Using list() or tuple() on a range object forces all the values to be returned at once. This is rarely necessary, and if the list is long, it can waste time and memory.

但是,当在较大应用程序中的代码中使用range()时,通常以这种方式使用list()tuple()被认为是较差的做法。 与迭代器一样, range对象也是惰性的-指定范围内的值只有在被请求之前才生成。 在range对象上使用list()tuple()强制立即返回所有值。 这很少需要,并且如果列表很长,则会浪费时间和内存。

range(<begin>, <end>, <stride>) returns an iterable that yields integers starting with <begin>, up to but not including <end>. If specified, <stride> indicates an amount to skip between values (analogous to the stride value used for string and list slicing):

range(<begin>, <end>, <stride>)返回一个可迭代的变量,该整数产生一个以<begin>整数,直到但不包括<end> 。 如果指定, <stride>表示在值之间跳过的量(类似于用于字符串和列表切片的stride值):

>>>
>>> list(range(5, 20, 3))[5, 8, 11, 14, 17]
>>>

If <stride> is omitted, it defaults to 1:

如果省略<stride> ,则默认为1

>>>
>>> list(range(5, 10, 1))[5, 6, 7, 8, 9]>>> list(range(5, 10))[5, 6, 7, 8, 9]
>>>

All the parameters specified to range() must be integers, but any of them can be negative. Naturally, if <begin> is greater than <end>, <stride> must be negative (if you want any results):

指定给range()所有参数都必须为整数,但其中任何一个都可以为负数。 自然地,如果<begin>大于<end> ,则<stride>必须为负(如果需要任何结果):

>>>
>>> list(range(-5, 5))[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]>>> list(range(5, -5))[]>>> list(range(5, -5, -1))[5, 4, 3, 2, 1, 0, -1, -2, -3, -4]
>>>

Technical Note: Strictly speaking, range() isn’t exactly a built-in function. It is implemented as a callable class that creates an immutable sequence type. But for practical purposes, it behaves like a built-in function.

技术说明:严格来说, range()并不是一个内置函数。 它被实现为创建不可变序列类型的可调用类。 但是出于实际目的,它的行为类似于内置函数。

For more information on range(), see the Real Python article .

有关range()更多信息,请参见Real Python文章 。

改变for循环行为 (Altering for Loop Behavior)

You saw in the previous tutorial in this introductory series how execution of a while loop can be interrupted with and modified with an . These capabilities are available with the for loop as well.

在本入门系列的上一教程中,您已经看到了while循环的执行如何被中断, 如何使用修改。 这些功能也可for循环。

breakcontinue声明 (The break and continue Statements)

break and continue work the same way with for loops as with while loops. break terminates the loop completely and proceeds to the first statement following the loop:

使用for循环和while循环以相同的方式breakcontinue工作。 break完全终止循环,并继续执行循环后的第一条语句:

>>>
>>> for i in ['foo', 'bar', 'baz', 'qux']:...     if 'b' in i:...         break...     print(i)...foo
>>>

continue terminates the current iteration and proceeds to the next iteration:

continue终止当前迭代并继续进行下一个迭代:

>>>
>>> for i in ['foo', 'bar', 'baz', 'qux']:...     if 'b' in i:...         continue...     print(i)...fooqux
>>>

else条款 (The else Clause)

A for loop can have an else clause as well. The interpretation is analogous to that of a while loop. The else clause will be executed if the loop terminates through exhaustion of the iterable:

for循环也可以具有else子句。 解释类似于while循环。 如果循环通过穷尽可迭代终止,则将执行else子句:

>>>
>>> for i in ['foo', 'bar', 'baz', 'qux']:...     print(i)... else:...     print('Done.')  # Will execute...foobarbazquxDone.
>>>

The else clause won’t be executed if the list is broken out of with a break statement:

如果列表是使用break语句中断的,则else子句不会执行:

>>>
>>> for i in ['foo', 'bar', 'baz', 'qux']:...     if i == 'bar':...         break...     print(i)... else:...     print('Done.')  # Will not execute...foo
>>>

结论 (Conclusion)

This tutorial presented the for loop, the workhorse of definite iteration in Python.

本教程介绍了for循环,它是Python中确定迭代的主力。

You also learned about the inner workings of iterables and iterators, two important object types that underlie definite iteration, but also figure prominently in a wide variety of other Python code.

您还了解了IterablesIterators的内部工作原理,这两个重要的对象类型是确定迭代的基础,但在其他各种Python代码中也占有重要地位。

In the next two tutorials in this introductory series, you will shift gears a little and explore how Python programs can interact with the user via input from the keyboard and output to the console.

在这个入门系列的下两个教程中,您将稍作调整,并探索Python程序如何通过键盘输入输出到控制台与用户交互。

翻译自:

转载地址:http://lzqwd.baihongyu.com/

你可能感兴趣的文章
SNMP从入门到开发:进阶篇
查看>>
@ServletComponentScan ,@ComponentScan,@Configuration 解析
查看>>
unity3d 射弹基础案例代码分析
查看>>
thinksns 分页数据
查看>>
os模块
查看>>
LINQ to SQL vs. NHibernate
查看>>
基于Angular5和WebAPI的增删改查(一)
查看>>
windows 10 & Office 2016 安装
查看>>
最短路径(SP)问题相关算法与模板
查看>>
js算法之最常用的排序
查看>>
Python——交互式图形编程
查看>>
经典排序——希尔排序
查看>>
团队编程项目作业2-团队编程项目代码设计规范
查看>>
英特尔公司将停止910GL、915GL和915PL芯片组的生产
查看>>
Maven配置
查看>>
HttpServletRequest /HttpServletResponse
查看>>
SAM4E单片机之旅——24、使用DSP库求向量数量积
查看>>
从远程库克隆库
查看>>
codeforces Unusual Product
查看>>
hdu4348 - To the moon 可持久化线段树 区间修改 离线处理
查看>>