你问你的代码将打印:
请向我解释如何变量,“伯爵”,自动将自己用字符串,各项指标联系起来“你好!”
但是在你的代码中,不需要使用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
有了上面的代码,你可以看到,计数会自动字符串“的各项指标相关联你好!”。但是,例如,如果将计数值设置为1,则第1个索引(Index0)字符串与count = 1时相关联,然后将其值与for循环索引的结尾相乘。
在“你好!”字符串有6个项目。第一项索引总是从0开始。但是为了打印更漂亮的显示,比如'第一项,第二项,第三项...',您可以添加一个计数变量,或者可以使用枚举函数,如下面的示例:
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
你是什么意思的“自动关联”办???它只是从0计数。 –
'H = [1]'???什么?同样,循环的每次迭代'count'变量都会增加1.简单地通过将1加到循环体的第一行。 –
'在ltr中打招呼[:: 2]:print(ltr)'会打印每一个字母......也......不太清楚这个程序的重点是什么 –