如何在 Python 3 中构建 For 循环

在计算机编程中使用循环使我们能够自动化和重复类似的任务多次,在本教程中,我们将涵盖Python的 for loop

一个)**是基于条件的。

前提条件

您应该在您的计算机或服务器上安装 Python 3 并设置一个编程环境. 如果您没有设置编程环境,可以指: [本地编程环境] (https://www.digitalocean.com/community/tutorial_series/how-to-install-and-set-up-a-local-programming-environment-for-python-3) 或适合您操作系统的 [服务器上的编程环境] (https://www.digitalocean.com/community/tutorial_collections/how-to-install-python-3-and-set-up-a-programming-environment (Ubuntu, CentOS, Debian等) 的安装和设置指南

对于路径

在Python中,for循环是这样构建的:

1for [iterating variable] in [sequence]:
2    [do something]

正在完成的东西将执行,直到序列结束。

要跟随本教程中的示例代码,请通过运行python3命令在本地系统上打开一个Python互动壳,然后您可以复制、粘贴或编辑示例,通过在>>>提示后添加它们。

让我们看看一个循环,它通过一系列值重复:

1for i in range(0,5):
2   print(i)

当我们运行这个程序时,输出会产生以下内容:

1[secondary_label Output]
20
31
42
53
64

这个循环将i设置为其迭代变量,序列存在于0至5的范围内。

然后在循环中,我们打印每循环迭代一个整数,请记住,在编程中,我们倾向于从指数0开始,所以尽管打印了5个数字,但它们从0到4之间。

你通常会看到和使用循环,当程序需要重复一个代码块几次。

对于使用 range() 的循环

Python 内置的不可变序列类型之一是 range(). 在循环中, range() 用于控制循环会重复多少次。

在使用 range() 时,您可以将 1 到 3 个整数参数传递给它:

  • start 表示序列开始的整数值,如果不包含,则 start 开始于 0 * stop 总是需要并且是数到但不包含的整数 * step 设置下一个迭代增加多少(或减少在负数的情况下),如果被省略,则 step 默认为 1

我们将审查一些通过不同参数到范围()的例子。

首先,让我们只通过):

1for i in range(6):
2   print(i)

在上面的程序中,):

1[secondary_label Output]
20
31
42
53
64
75

接下来,我们将看看范围(开始,停止),其值将传递给迭代何时应该开始以及何时应该停止:

1for i in range(20,25):
2   print(i)

在这里,范围从20(包括)到25(专属),因此输出如下:

1[secondary_label Output]
220
321
422
523
624

「範圍()」的「步驟」論點類似於(https://andsky.com/tech/tutorials/how-to-index-and-slice-strings-in-python-3# specifying-stride-while-slicing-strings)在於它可以用來跳過序列中的值。

在所有三个参数中,)`。

1for i in range(0,15,3):
2   print(i)

在这种情况下,循环设置为从0到15的数字打印出来,但在3的步骤上,所以只有每一个第三个数字被打印出来,如下:

1[secondary_label Output]
20
33
46
59
612

我们还可以使用负值来重复我们的步骤参数,但我们必须相应地调整我们的开始停止参数:

1for i in range(100,0,-10):
2   print(i)

在这里,100是开始值,0是停止值,10是范围,所以循环从100开始,到0结束,每次迭代都会减少10。

 1[secondary_label Output]
 2100
 390
 480
 570
 660
 750
 840
 930
1020
1110

在Python中编程时,)`序列类型作为其迭代参数。

用于使用序列数据类型的循环

Lists和其他数据序列类型也可以作为for循环中的迭代参数利用。

我们会将列表分配给一个变量,然后通过列表重复:

1sharks = ['hammerhead', 'great white', 'dogfish', 'frilled', 'bullhead', 'requiem']
2
3for shark in sharks:
4   print(shark)

虽然我们使用的变量是),我们会得到相同的输出:

1[secondary_label Output]
2hammerhead
3great white
4dogfish
5frilled
6bullhead
7requiem

上面的输出显示for循环通过列表重复,并按行打印了列表中的每个项目。

列表和其他以序列为基础的 数据类型stringstuples 通常用于循环,因为它们可以重复使用。 您可以将这些数据类型与 range() 结合到列表中,例如:

1sharks = ['hammerhead', 'great white', 'dogfish', 'frilled', 'bullhead', 'requiem']
2
3for item in range(len(sharks)):
4   sharks.append('shark')
5
6print(sharks)
1[secondary_label Output]
2['hammerhead', 'great white', 'dogfish', 'frilled', 'bullhead', 'requiem', 'shark', 'shark', 'shark', 'shark', 'shark', 'shark']

在这里,我们为鲨鱼列表的长度的每个项目添加了鲨鱼的字符串。

您还可以使用for循环从头开始构建列表:

1integers = []
2
3for i in range(10):
4   integers.append(i)
5
6print(integers)

在此示例中,列表整数是初始化为空的,但循环填充了列表,如下:

1[secondary_label Output]
2[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

同样,我们可以通过字符串迭代:

1sammy = 'Sammy'
2
3for letter in sammy:
4   print(letter)
1[secondary_label Output]
2S
3a
4m
5m
6y

通过 tuples复制是通过上面的列表或字符串复制的相同格式进行的。

当通过字典(https://andsky.com/tech/tutorials/understanding-dictionaries-in-python-3)重复时,重要的是要记住密钥 :值结构,以确保您在召唤字典的正确元素。

1sammy_shark = {'name': 'Sammy', 'animal': 'shark', 'color': 'blue', 'location': 'ocean'}
2
3for key in sammy_shark:
4   print(key + ': ' + sammy_shark[key])
1[secondary_label Output]
2name: Sammy
3animal: shark
4location: ocean
5color: blue

在使用具有for循环的字典时,迭代变量对应于字典的键,而dictionary_variable[iterating_variable]对应于值。

循环通常用于迭代和操纵序列数据类型。

为了路径

循环可以在Python中嵌入,就像其他编程语言一样。

一个嵌入式循环是另一个循环内发生的循环,结构上类似于(https://andsky.com/tech/tutorials/how-to-write-condition-statements-in-python-3-2# nested-if-statements)。

1for [first iterating variable] in [outer loop]: # Outer loop
2    [do something]  # Optional
3    for [second iterating variable] in [nested loop]:   # Nested loop
4        [do something]

程序首先遇到外环,执行它的第一个迭代. 这个第一次迭接触发了内部的,被巢绕的环,再跑到完成. 然后程序返回到外环上方,完成第二次迭接并再次触发被巢接的环. 再次,被嵌入的循环会运行到完成,程序会返回到外循环的顶端,直到序列完成或者一个[断 (https://andsky.com/tech/tutorials/how-to-use-break-continue-and-pass-statements-when-working-with-loops-in-python-3# break-statement)或其他语句会扰乱进程.

在本示例中,外部循环将通过名为num_list的整数列表迭代,而内部循环将通过名为alpha_list的字符串列表迭代。

1num_list = [1, 2, 3]
2alpha_list = ['a', 'b', 'c']
3
4for number in num_list:
5    print(number)
6    for letter in alpha_list:
7        print(letter)

当我们运行这个程序时,我们将收到以下输出:

 1[secondary_label Output]
 21
 3a
 4b
 5c
 62
 7a
 8b
 9c
103
11a
12b
13c

输出显示,该程序通过打印1来完成外环的第一次迭代,然后触发内环的完成,连续打印a,b,c

在由列表组成的列表中,如果我们只使用一个for循环,程序将输出每个内部列表作为一个项目:

1list_of_lists = [['hammerhead', 'great white', 'dogfish'],[0, 1, 2],[9.9, 8.8, 7.7]]
2
3for list in list_of_lists:
4    print(list)
1[secondary_label Output]
2['hammerhead', 'great white', 'dogfish']
3[0, 1, 2]
4[9.9, 8.8, 7.7]

为了访问内部列表中的每个单个项目,我们将实现嵌入的for循环:

1list_of_lists = [['hammerhead', 'great white', 'dogfish'],[0, 1, 2],[9.9, 8.8, 7.7]]
2
3for list in list_of_lists:
4    for item in list:
5        print(item)
 1[secondary_label Output]
 2hammerhead
 3great white
 4dogfish
 50
 61
 72
 89.9
 98.8
107.7

当我们使用嵌入的for循环时,我们可以重复列表中包含的个别项目。

我们可以在我们关于自然语言处理工具包(NLTK)的教程中看到在工作程序中使用的嵌入 for 环节(https://andsky.com/tech/tutorials/how-to-work-with-language-data-in-python-3-using-the-natural-language-toolkit-nltk# step-5-%E2%80%94-counting-pos-tags)。

结论

本教程介绍了Python中的for循环是如何工作的,以及如何构建它们。

从这里,你可以继续通过阅读教程在 (https://andsky.com/tech/tutorials/how-to-construct-while-loops-in-python-3) 和** (https://andsky.com/tech/tutorials/how-to-use-break-continue-and-pass-statements-when-working-with-loops-in-python-3)读取有关循环的信息。

要在项目中使用循环,请跟随以下教程:

Published At
Categories with 技术
comments powered by Disqus