Python 简明教程

Python - For Loops

在 Python 中, for loop 可循环遍历任何序列(例如列表、元组或字符串)中的项。它对序列的每一项执行相同的操作。此循环以 for 关键字开头,后跟一个变量(用于表示序列中的当前项)。 in 关键字将变量链接到你想要迭代的序列。 colon (:) 用在循环头的末尾,其下方的缩进代码块将针对序列中的每一项执行一次。

The for loop in Python provides the ability to loop over the items of any sequence, such as a list, tuple or a string. It performs the same action on each item of the sequence. This loop starts with the for keyword, followed by a variable that represents the current item in the sequence. The in keyword links the variable to the sequence you want to iterate over. A colon (:) is used at the end of the loop header, and the indented block of code beneath it is executed once for each item in the sequence.

Syntax of Python for Loop

for iterating_var in sequence:
   statement(s)

在这里,iterating_var 是一个变量,将在每次迭代期间为其分配每个序列项的值。Statements 表示你希望重复执行的代码块。

Here, the iterating_var is a variable to which the value of each sequence item will be assigned during each iteration. Statements represents the block of code that you want to execute repeatedly.

在循环开始前,将评估序列。如果它是一个列表,则首先评估表达式列表(如有)。然后,将序列中的第一个项(在索引 0 处)分配给 iterating_var 变量。

Before the loop starts, the sequence is evaluated. If it’s a list, the expression list (if any) is evaluated first. Then, the first item (at index 0) in the sequence is assigned to iterating_var variable.

在每次迭代期间,使用 iterating_var 的当前值执行语句块。在此之后,将序列中的下一项分配给 iterating_var,循环将继续进行,直至整个序列都用尽。

During each iteration, the block of statements is executed with the current value of iterating_var. After that, the next item in the sequence is assigned to iterating_var, and the loop continues until the entire sequence is exhausted.

Flowchart of Python for Loop

以下流程图说明了 for 循环的工作原理 −

The following flow diagram illustrates the working of for loop −

forloop

Python for Loop with Strings

string 是一个 Unicode 字母序列,每个字母都有一个位置索引。因为它是序列,所以你可以使用 for 循环遍历其字符。

A string is a sequence of Unicode letters, each having a positional index. Since, it is a sequence, you can iterate over its characters using the for loop.

Example

以下示例比较每个字符,并显示它是否不是元音('a'、'e'、'i'、'o'、'u')。

The following example compares each character and displays if it is not a vowel ('a', 'e', 'i', 'o', 'u').

zen = '''
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
'''
for char in zen:
   if char not in 'aeiou':
      print (char, end='')

执行此代码后,会生成以下输出 −

On executing, this code will produce the following output −

Btfl s bttr thn gly.
Explct s bttr thn mplct.
Smpl s bttr thn cmplx.
Cmplx s bttr thn cmplctd.

Python for Loop with Tuples

Python’s tuple 对象也是索引序列,因此你可以使用 for 循环遍历其项。

Python’s tuple object is also an indexed sequence, and hence you can traverse its items with a for loop.

Example

在以下示例中,for 循环遍历包含整数的元组,并返回所有数字的总和。

In the following example, the for loop traverses a tuple containing integers and returns the total of all numbers.

numbers = (34,54,67,21,78,97,45,44,80,19)
total = 0
for num in numbers:
   total += num
print ("Total =", total)

运行这段代码时,它将产生以下输出 −

On running this code, it will produce the following output −

Total = 539

Python for Loop with Lists

Python’s list 对象也是索引序列,因此你可以使用 for 循环遍历其项。

Python’s list object is also an indexed sequence, and hence you can iterate over its items using a for loop.

Example

在以下示例中,for 循环遍历包含整数的列表,并且仅打印可被 2 整除的那些整数。

In the following example, the for loop traverses a list containing integers and prints only those which are divisible by 2.

numbers = [34,54,67,21,78,97,45,44,80,19]
total = 0
for num in numbers:
   if num%2 == 0:
      print (num)

当你执行代码时,将显示以下结果 −

When you execute this code, it will show the following result −

34
54
78
44
80

Python for Loop with Range Objects

Python 的内置 range() 函数返回一个迭代器对象,该对象流式传输一个数字序列。该对象包含从 start 到 stop 的整数(以 step 参数分隔)。你也可以使用 for 循环运行 range。

Python’s built-in range() function returns an iterator object that streams a sequence of numbers. This object contains integers from start to stop, separated by step parameter. You can run a for loop with range as well.

Syntax

range() 函数具有以下语法 −

The range() function has the following syntax −

range(start, stop, step)

其中,

Where,

  1. Start − Starting value of the range. Optional. Default is 0

  2. Stop − The range goes upto stop-1

  3. Step − Integers in the range increment by the step value. Option, default is 1.

Example

在这个示例中,我们将看到 range 与 for 循环一起使用。

In this example, we will see the use of range with for loop.

for num in range(5):
   print (num, end=' ')
print()
for num in range(10, 20):
   print (num, end=' ')
print()
for num in range(1, 10, 2):
   print (num, end=' ')

当运行以上代码时,它会产生以下输出 −

When you run the above code, it will produce the following output −

0 1 2 3 4
10 11 12 13 14 15 16 17 18 19
1 3 5 7 9

Python for Loop with Dictionaries

与列表、元组或字符串不同,Python 中的 dictionary 数据类型不是序列,因为项目没有位置索引。但是,仍然可以使用 for 循环遍历字典。

Unlike a list, tuple or a string, dictionary data type in Python is not a sequence, as the items do not have a positional index. However, traversing a dictionary is still possible with the for loop.

Example

对字典对象运行一个简单的 for 循环可遍历其中使用的键。

Running a simple for loop over the dictionary object traverses the keys used in it.

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers:
   print (x)

执行后,此代码将会产生以下 output

On executing, this code will produce the following output

10
20
30
40

一旦获取到键,就可以通过使用方括号运算符或 get() 方法轻松访问与其关联的值。

Once we are able to get the key, its associated value can be easily accessed either by using square brackets operator or with the get() method.

Example

以下示例说明了上述方法。

The following example illustrates the above mentioned approach.

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers:
   print (x,":",numbers[x])

它将生成以下 output

It will produce the following output

10 : Ten
20 : Twenty
30 : Thirty
40 : Forty

dict 类的 items()、keys() 和 values() 方法分别返回视图对象 dict_items、dict_keys 和 dict_values。这些对象是迭代器,因此我们可以使用 for 循环来遍历它们。

The items(), keys() and values() methods of dict class return the view objects dict_items, dict_keys and dict_values respectively. These objects are iterators, and hence we can run a for loop over them.

Example

dict_items 对象是一个可以像下面这样遍历键值元组的列表——

The dict_items object is a list of key-value tuples over which a for loop can be run as follows −

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers.items():
   print (x)

它将生成以下 output

It will produce the following output

(10, 'Ten')
(20, 'Twenty')
(30, 'Thirty')
(40, 'Forty')

Using else Statement with For Loop

Python 支持将一个 else 语句与一个循环语句关联。但是,在循环耗尽列表的迭代时执行 else 语句。

Python supports to have an else statement associated with a loop statement. However, the else statement is executed when the loop has exhausted iterating the list.

Example

以下示例说明了 else 语句与 for 语句的组合,它用于搜索 10 到 20 之间素数。

The following example illustrates the combination of an else statement with a for statement that searches for prime numbers from 10 to 20.

#For loop to iterate between 10 to 20
for num in range(10, 20):
   #For loop to iterate on the factors
   for i in range(2,num):
      #If statement to determine the first factor
      if num%i == 0:
         #To calculate the second factor
         j=num/i
         print ("%d equals %d * %d" % (num,i,j))
         #To move to the next number
         break
      else:
         print (num, "is a prime number")
         break

执行上述代码后,将生成以下结果 −

When the above code is executed, it produces the following result −

10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number