我写东西的时候不懂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代替名字时,输出会完全改变
在第一个循环中,您正在打印
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个版本中的打字错误。你知道吗相关问题 更多 >
编程相关推荐