numberlist = [1, 4, 7, 5, 6, 2, 4]
for i in numberlist:
pos = numberlist.index(i)
next = pos + 1
ordering = [i, numberlist[next]]
print(ordering)这是我有问题的代码。当我运行它时,它应该打印包含两个项的多个列表:I的值和后面的数字。但是,在最后一次迭代中添加了一个额外的数字,并且它可能是哪个数字没有一致性,在这种情况下,输出是:
[1, 4]
[4, 7]
[7, 5]
[5, 6]
[6, 2]
[2, 4]
[4, 7]A 7是在末尾添加的,虽然我认为它可能只是重复列表中已经出现的一个数字,但是如果我在列表中添加另一个值,
numberlist = [1, 4, 7, 5, 6, 2, 4, 6]产出如下:
[1, 4]
[4, 7]
[7, 5]
[5, 6]
[6, 2]
[2, 4]
[4, 7]
[6, 2]添加了一个2,但是列表中没有2。我还注意到,没有考虑到6,它再次打印7。但是,如果不是6,而是添加了一个3,代码就会给我一个错误,正如它应该的那样。
File "c:/Users/santi/Desktop/code/order/#test zone.py", line 8, in <module>
ordering = [i, numberlist[next]]
IndexError: list index out of range这里发生了什么事?
发布于 2022-07-17 09:25:52
numberlist = [1, 4, 7, 5, 6, 2, 4]根据示例和for循环,列表中有7个元素。
一旦我是6,这是名单上的最后一个位置,它仍然将执行所有的代码在for循环中。我可以建议的是使用一个if条件来中断for循环,当它到达列表中的最后一个元素时。
numberlist = [1, 4, 7, 5, 6, 2, 4]
for position, number in enumerate(numberlist):
# Break for loop once it is the last position
# Need to -1 from len() function as index position is from 0 to 6
if position == len(numberlist) - 1:
break
# proceed to next position with += 1
position += 1
ordering = [number, numberlist[position]]
print(ordering)https://stackoverflow.com/questions/73010561
复制相似问题