[英]Why does list in program give an unexpected output?
I am having a problem with my list in python.我在 python 中的列表有问题。
I am printing out the list (working), a number that shows the line number (working) and an item in the list that should change every time the list is printed(not working?)我正在打印列表(工作),一个显示行号(工作)的数字和列表中的一个项目,每次打印列表时都应该更改(不工作?)
a = ["A", "B", "C", "D", "E"]
b = 0
for x in a:
while b <= 10:
print(a, x, b)
b += 1
My current program output is我当前的程序输出是
['A', 'B', 'C', 'D', 'E'] A 0
['A', 'B', 'C', 'D', 'E'] A 1
['A', 'B', 'C', 'D', 'E'] A 2
['A', 'B', 'C', 'D', 'E'] A 3
so on很快
the output I would like我想要的输出
['A', 'B', 'C', 'D', 'E'] A 0
['A', 'B', 'C', 'D', 'E'] B 1
['A', 'B', 'C', 'D', 'E'] C 2
['A', 'B', 'C', 'D', 'E'] D 3
and so on Although, when I try a different program it works perfectly?等等 虽然,当我尝试不同的程序时,它可以完美运行吗?
list = ["a", "b", "c"]
for a in list:
print(a)
Why does this happen and how can I fix it?为什么会发生这种情况,我该如何解决?
That is because you have the while
loop inside the outer for
loop (that iterates over the elements of the list. So the inner while loop only exists when b becomes greater than 10
, and till then the value of x
is A
.那是因为您在外部
for
循环中有while
循环(它遍历列表的元素。因此内部 while 循环仅在 b 大于10
时才存在,直到那时x
值为A
。
For what you want I would suggest using itertools.cycle()
.对于你想要的,我建议使用
itertools.cycle()
。 Example -例子 -
>>> a = ["A", "B", "C", "D", "E"]
>>>
>>> b = 0
>>> import itertools
>>> acycle = itertools.cycle(a)
>>> for i in range(11):
... print(a,next(acycle),i)
...
['A', 'B', 'C', 'D', 'E'] A 0
['A', 'B', 'C', 'D', 'E'] B 1
['A', 'B', 'C', 'D', 'E'] C 2
['A', 'B', 'C', 'D', 'E'] D 3
['A', 'B', 'C', 'D', 'E'] E 4
['A', 'B', 'C', 'D', 'E'] A 5
['A', 'B', 'C', 'D', 'E'] B 6
['A', 'B', 'C', 'D', 'E'] C 7
['A', 'B', 'C', 'D', 'E'] D 8
['A', 'B', 'C', 'D', 'E'] E 9
['A', 'B', 'C', 'D', 'E'] A 10
You have a double loop here ( while
inside for
) and you never reset the b
to 0. To get the result you expected, you should use enumerate
:您在这里有一个双循环(
while
在for
内部)并且您永远不会将b
重置为 0。要获得您预期的结果,您应该使用enumerate
:
for idx, x in enumerate(a):
print(a, x, idx)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.