Python基本循环迭代

肖恩

请向我解释变量“count”如何自动与字符串“Hello!”的每个索引相关联。

greeting = 'Hello!'
count = 0

for letter in greeting:
    count += 1
    if count % 2 == 0:
        print(letter)
    print(letter)

print('done')

基本上,以下问题询问字符串中每个字母的打印次数。查了讨论区,发现逻辑是输出H = [1], e = [2], l = [3], l = [4], o = [5], ! = [6]。问题是,我不明白为什么会发生这种情况。

胆汁酸

您询问:

请向我解释变量“count”如何自动与字符串“Hello!”的每个索引相关联。

但是在您的代码中,不需要使用 if 语句。并且您应该将索引或计数添加到字符串项目的附近。简单的代码应该是这样的:

greeting = 'Hello!'
count = 0
for item in greeting:
    print("item={}, index={}, count={:d}".format(item,greeting.index(item),count))
    count += 1

这将打印出:

item=H, index=0, count=0
item=e, index=1, count=1
item=l, index=2, count=2
item=l, index=2, count=3
item=o, index=4, count=4
item=!, index=5, count=5

通过上面的代码,您可以看到计数自动与字符串“Hello!”的每个索引相关联。但是,当您将计数值设置为例如 1 时,第一个索引 (Index0) 字符串与 count=1 相关联,然后将其值乘以 for 循环直到索引结束。

在“你好!” 字符串有6个项目。第一个项目索引总是从 0 开始。但是为了打印更漂亮的显示,比如“第一项,第二项,第三项......”你可以添加一个计数变量,或者你可以像下面的例子一样使用 enumerate 函数:

greeting = 'Hello!'
count = 1
for item in greeting:
    print("item={}, index={}, count={:d}".format(item,greeting.index(item),count))
    count += 1

greeting = 'Hello!'
for count,item in enumerate(greeting,1):
    print("item={}, index={}, count={:d}".format(item,greeting.index(item),count)) 

最后两个代码会给你相同的结果,它们是:

item=H, index=0, count=1
item=e, index=1, count=2
item=l, index=2, count=3
item=l, index=2, count=4
item=o, index=4, count=5
item=!, index=5, count=6

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章