艺赛旗 RPA8.0全新首发免费下载 点击下载
http://www.i-search.com.cn/index.html?from=line1 详细内容请参看艺赛旗官网支持栏目:RPA社区
点击链接进入 http://support.i-search.com.cn/
- 遍历列表
需要对列表中的每个元素都执行相同的操作时,可使用 for 循环:
magicians = [‘alice’,‘david’,‘carolina’]
for magician in magicians:
print(magician)
alice
david
carolina
循环中,Python 将首先读取其中的第一行代码:
for magician in magicians:
这行代码让 Python 获取列表 magicians 中的第一个值(‘alice’ ),并将其存储到变量 magician 中。接下来,Python 读取下一行代码:
print(magician)
它让 Python 打印 magician 的值——依然是’alice’ 。鉴于该列表还包含其他值,Python 返回到循环的第一行:
for magician in magicians:
Python 获取列表中的下一个名字——‘david’ ,并将其存储到变量 magician 中,再执行下面这行代码:
print(magician)
以此类推,直至列表的最后一个元素。
对列表中的每个元素,都将执行循环指定的步骤,而不管列表包含多少个元素。如果列表包含一百万个元素,Python 就重复执行指定的步骤一百万次,且通常速度非常快。 使用 for 循环处理数据是一种对数据集执行整体操作的不错的方式。
- 避免缩进错误,Python 根据缩进来判断代码行与前一个代码行的关系
2.1 未缩进:
magicians = [‘alice’,‘david’,‘carolina’]
for magician in magicians:
print(magician)
IndentationError: expected an indented bl