Home >Backend Development >Python Tutorial >Detailed explanation of the use of for loop in Python_python

Detailed explanation of the use of for loop in Python_python

不言
不言Original
2018-04-04 17:29:325526browse

This article mainly introduces the use of for loop in Python. It comes from the technical documentation of IBM official website. Friends in need can refer to it

for loop

The previous article in this series, "Exploring Python, Part 5: Programming in Python," discussed if statements and while loops, discussed compound statements, and the appropriate indentation of Python statements to indicate related blocks of Python code. The article ends with an introduction to the Python for loop. But in terms of its use and function, the for loop deserves more attention, so this article discusses this loop separately.

The for loop has a simple syntax that allows you to extract a single item from a container object and perform certain operations on it. Simply put, using a for loop, you iterate over the items in a collection of objects. A collection of objects can be any Python container type, including the tuple, string, and list types discussed in the previous article. But the container metaphor is more powerful than these three types. Metaphors include other sequence types such as dictionary and set, which will be discussed in future articles.

But please wait! There's more: for loops can be used to iterate over any object that supports the iteration metaphor, which makes for loops very useful.

Listing 1 shows the basic syntax of a for loop and also demonstrates how to use continue and break statements in a for loop.
Listing 1. Pseudocode for a for loop

for item in container:
 
  if conditionA:    # Skip this item
    continue
 
  elif conditionB:   # Done with loop
    break
 
  # action to repeat for each item in the container
 
else:
 
  # action to take once we have finished the loop.

The second article in this series, “Exploring Python, Part 2: Exploring Python Types Hierarchies" introduces Python tuples. As mentioned in the article, tuple types are immutable heterogeneous containers. This mainly means that a tuple can store objects of different types, but once it is created, it cannot be changed. Listing 2 demonstrates how to use a for loop to iterate over the elements of a tuple.
Listing 2. for loop and tuple

>>> t = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) 
>>> count = 0
>>> for num in t:
...   count += num
... else:
...   print count
... 
45
>>> count = 0
>>> for num in t:
...   if num % 2:
...     continue
...   count += num
... else:
...   print count
... 
20

This example first creates a tuple named t to store the integers 0 to 9 (including 9). The first for loop iterates over the tuple, accumulating the sum of the values ​​in the tuple in the count variable. Once the code has iterated through all the elements in the tuple, it enters the else clause of the for loop and prints the value of the count variable.

The second for loop shown in Listing 2 also iterates over all elements in the tuple. However, it only accumulates the values ​​of those items in the container that are divisible by 2 (remember that the if statement is true if the expression is nonzero, and using the % operator when num is not divisible by 2 will return a nonzero value) . This restriction is accomplished by using appropriate if statements and continue statements. As mentioned in the previous article, the continue statement causes the loop containing it to begin the next iteration. Another way to achieve the same result is to test whether the current item in the tuple is an even number (using if not num % 2:), and if true, then add the current item to the running sum. Once the code completes iterating through the tuple, the else clause is called, printing the sum.

The third article in this series, "Exploring Python: Part 3: Exploring the Python Type Hierarchy," discusses Python strings. String is an immutable isomorphic container, which means it can only hold characters and cannot be modified once created. Listing 3 demonstrates how to use a Python string as a container for a for loop.
Listing 3. for loops and string

>>> st = "Python Is A Great Programming Language!"
>>> for c in st:
...   print c,
... 
P y t h o n  I s  A  G r e a t  P r o g r a m m i n g  L a n g u a g e !
>>> count = 0
>>> for c in st:
...   if c in "aeiou":
...     count += 1
... else:
...   print count
...
10
>>> count = 0
>>> for c in st.lower():
...   if c in "aeiou":
...     count += 1
... else:
...   print count
... 
12

This example provides three different for loops that all iterate over the same string. The first for loop iterates over the string "Python Is A Great Programming Language!" and prints the string one character at a time. In this example, a comma is appended to the print statement variable c. This causes the print statement to print character values ​​followed by a space character instead of a newline character. Without the following comma, the characters would all be printed on separate lines, which would be difficult to read.

The next two for loops iterate over the string and count how many vowels ("a", "e", "i", "o", or "u") it contains. The second for loop only looks for lowercase vowels when iterating over the original string. The third for loop iterates over the temporary string returned by calling the lower method of the string object. The lower method converts all characters in string to lowercase. Therefore, the third for loop finds two more vowels.

The fourth article in this series, "Exploring Python, Part 4: Exploring the Python Type Hierarchy," introduces Python lists. A list is a heterogeneous mutable container, which means it can store objects of different types and can be modified after creation. Listing 4 demonstrates how to use a list and a for loop.
Listing 4. The for loop and list

>>> mylist = [1, 1.0, 1.0j, '1', (1,), [1]]
>>> for item in mylist:
...   print item, "\t", type(item))
... 
1    <type &#39;int&#39;>
1.0   <type &#39;float&#39;>
1j   <type &#39;complex&#39;>
1    <type &#39;str&#39;>
(1,)  <type &#39;tuple&#39;>
[1]   <type &#39;list&#39;>

Since list is a very flexible Python container type (you will use it many times in the rest of this series see it), this example may seem too simplistic. But, here's part of the point: using a for loop makes it very simple to process each item in the container, even a list containing a variety of different objects. This example iterates over all items in a Python list and prints each item and its corresponding Python type on a separate line.
Iteration and mutable containers

Python list 是一个可变序列,提供了一种令人好奇的可能性:for 循环主体可以修改其正在迭代的 list。正如您可能认为的,这样并不好,如果进行此操作,Python 解释器将无法很好地工作,如清单 5 所示。
清单 5. 在 for 循环中修改容器

>>> mylist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for item in mylist:
...   if item % 2:
...     mylist.insert(0, 100)
... 
^CTraceback (most recent call last):
 File "<stdin>", line 3, in ?
KeyboardInterrupt
>>> print mylist
[100, ...., 100, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Many lines deleted for clarity
>>> mylist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for item in mylist[:]:
...   if item % 2:
...     mylist.insert(0, 100)
... 
>>> print mylist
[100, 100, 100, 100, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

本例中的第一个 for 循环只要在原始 list 中发现奇数,它就在 list 的开始插入数值 100。当然,这是一种演示此问题的不同寻常的方式,但却非常好。一旦在三个点的 Python 提示后按 Enter 键,Python 解释器就处于无限循环的混乱中。要停止这种混乱,必须通过按 Ctrl-C(其在 Python 输出中显示为 ^C)来中断进程,然后会出现 KeyboardInterrupt 异常。如果打印出修改的 list,将看到 mylist 现在包含大量的值为 100 的元素(新元素的准确数量取决于您中断循环的速度)。

本例中的第二个 for 循环演示了如何避免此问题。使用切片运算符创建原始 list 的副本。现在 for 循环将迭代该副本,而对原始 list 进行修改。最终的结果是修改后的原始 list,它现在以五个值为 100 的新元素开始。

for 循环和序列索引

如果您用过其他编程语言,Python for 循环可能看起来有点儿古怪。您可能认为它更像 foreach 循环。基于 C 的编程语言具有 for 循环,但它的设计目的是对一系列操作执行特定次数。Python for 循环可以通过使用内置的 range 和 xrange 方法来模拟该行为。清单 6 中演示了这两种方法。
清单 6. range 和 xrange 方法

>>> r = range(10)
>>> print r
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> type(r)
<type &#39;list&#39;>
>>> xr = xrange(10)
>>> print xr
xrange(10)
>>> type(xr)
<type &#39;xrange&#39;>

本例首先演示了 range 方法,它创建一个包含一系列整数的新 list。调用 range 方法的一般形式是提供单个值,用作整数 list 的上限。零为起始值。因此,调用 range(10) 将创建包含整数 0 至 9(包含 9)的 list。range 方法接受起始索引以及步长。所以,调用 range(11,20) 将创建从 11 至 19(包含 19)的整数 list,而调用 range(12, 89, 2) 将创建从 12 至 88 的偶数 list。

由于 xrange 方法也创建整数 list(其使用相同参数),所以它与 range 方法非常相似。但是,xrange 方法仅在需要时才在 list 中创建整数。例如,在清单 6 中,尝试打印出新创建的 xrange 时除了 xrange 的名称,不会显示任何数据。当需要迭代大量整数时,xrange 方法更适用,因为它不会创建极大的 list,那样会消耗大量计算机内存。

清单 7 演示了如何在 for 循环内使用 range 方法来创建整数 1 至 10(包含 10)的乘法表。
清单 7. 创建乘法表

>>> for row in range(1, 11):
...   for col in range(1, 11):
...     print "%3d " % (row * col),
...   print
... 
 1  2  3  4  5  6  7  8  9  10 
 2  4  6  8  10  12  14  16  18  20 
 3  6  9  12  15  18  21  24  27  30 
 4  8  12  16  20  24  28  32  36  40 
 5  10  15  20  25  30  35  40  45  50 
 6  12  18  24  30  36  42  48  54  60 
 7  14  21  28  35  42  49  56  63  70 
 8  16  24  32  40  48  56  64  72  80 
 9  18  27  36  45  54  63  72  81  90 
 10  20  30  40  50  60  70  80  90 100

本例使用两个 for 循环,外面的 for 循环关注乘法表中的每一行,嵌套的 for 循环关注每行内的列。每个循环都迭代包含整数 1 至 10(包含 10)的 list。最里面的 print 语句使用了一个名为 字符串格式化 的新概念来创建格式设置精美的表。字符串格式化是一种非常有用的技术,用于以格式设置精美的布局创建由不同数据类型组成的 string。现在详细信息并不重要,将来的文章中将讲述这些内容(了解 C 编程语言的 printf 方法的任何人都会很熟悉这些内容)。在本例中,字符串格式化指定将从整数创建新 string 且需要保留三个字符来存放该整数(如果该整数小于三个字符,将在左边用空格填补,从而使数据排列整齐)。第二个 print 语句用于打印新行,从而使乘法表中的下一行被打印在新的行中。

range 方法还可用于迭代容器,通过使用适当的索引访问序列中的每一项。要进行此操作,需要包含容器的允许范围索引值的整数 list,这可以通过使用 range 方法和 len 方法来轻松实现,如清单 8 所示。
清单 8. 在 for 循环内索引容器

>>> st = "Python Is A Great Programming Language!"
>>> for index in range(len(st)): 
...   print st[index],
... 
P y t h o n  I s  A  G r e a t  P r o g r a m m i n g  L a n g u a g e !
>>> for item in st.split(&#39; &#39;):
...   print item, len(item)
... 
Python 6
Is 2
A 1
Great 5
Programming 11
Language! 9

这个最后的示例演示了如何使用 len 方法作为 range 方法的参数,创建可用于单独访问 string 中每个字符的整数 list。第二个 for 循环还显示了如何将 string 分割为子字符串的 list(使用空格字符来指示子字符串的边界)。for 循环迭代子字符串 list,打印每个子字符串及其长度。

结束语

本文讨论了 Python for 循环并演示了它的一些使用方式。可以将 for 循环与提供迭代器的任何 Python 对象结合使用,这些对象包括 tuple、string 和 list 等内置序列类型。for 循环和 list 序列一起使用时具有强大的功能,您会发现自己在许多情况中都要使用它们。Python 提供了用于组合这两个概念的简单机制,称为列表理解,将来的文章中将讲述该内容。

Related recommendations:

Usage and difference between for loop and foreach loop in PHP

js about nested for loop examples

The above is the detailed content of Detailed explanation of the use of for loop in Python_python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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