理解FORLOPS

2024-10-01 09:41:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我写东西的时候不懂for循环

names = ["Mark", "Cyr", "Hunt", "Dave", "Crock"] 

for name in names:
    print "Here is the list of criminals %r" %names

输出是这样的。你知道吗

Here is the list of criminals: Mark, Cyr, Hunt, Dave, Crock
Here is the list of criminals: Mark, Cyr, 'Hunt, Dave, Crock
Here is the list of criminals: Mark, Cyr, Hunt, Dave, Crock
Here is the list of criminals: Mark, Cyr, Hunt, Dave, Crock
Here is the list of criminals: Mark, Cyr, Hunt, Dave, Crock

但如果我稍微改变一下,像这样。你知道吗

for i in names:
    print "Here is the list of criminals: %r" %i

输出是这样的

Here is the list of criminals: Mark
Here is the list of criminals: Cyr
Here is the list of criminals: Hunt
Here is the list of criminals: Dave
Here is the list of criminals: Crock

但这是为什么。为什么当我用%i代替名字时,输出会完全改变


Tags: oftheinforherenamesislist
3条回答

在第一个循环中,您正在打印names,这是整个列表。因此,对于列表中的每个元素,您将打印整个列表。你知道吗

也许你想打印name?你知道吗

首先,你做了两件事:

  • 将循环变量name替换为i。你知道吗
  • 您将第二个操作数替换为格式化运算符%。它过去是names,现在是i。你知道吗

这意味着两件事:

  • 在执行for循环时,现在是i而不是name在每次迭代中获取names元素的值。你知道吗
  • 对于每次迭代,i中的值(即列表names的元素)由%运算符格式化为"Here is the list of criminals: %r"定义的格式,因此生成的打印字符串将"Here is the list of criminals: "附加i的值,而不是该字符串附加names中列表的整个值。你知道吗

是的。列表中有5个元素,因此for循环将循环5次。你知道吗

您的原始代码实际上是这样说的: 执行print语句5次。每次都把名为names的整个列表放在%r所在的位置。你知道吗

你的第二种说法是: 执行print语句5次。每次将当前名称(由名为i的变量表示)放在%r所在的位置。你知道吗

我猜names后面的“s”就是约翰提到的第1个版本中的打字错误。你知道吗

相关问题 更多 >