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)发布于 2022-07-17 12:33:52
这段代码非常有趣,因为它暴露了初学者将要遇到的一些问题。第一个是选择更有意义的变量名(参见注释),第二个是学习如何调试一个小程序。
之前的评论和帖子确实没有提到这些问题,尽管它们确实指出了这些症状。
用更有意义的变量名称修改OP代码,以演示意图并避免陷阱:
如果L列表不包含重复编号(本例中为4),则不问题将能够自己暴露出来。
L = [1, 4, 7, 5, 6, 2, 4]
# * *
for x in L: # use x to mean the extracted number. i is for index usually
next_pos = L.index(x) + 1
pair = [x, L[next_pos] ] # take current one and next num.
print(pair) # when it reached the end of L, 4 in the case, it will find the first 4 (pos. 1) and that's why you have pair (4, 7)打印相邻数字对的正确方法应该是:
L = [1, 4, 7, 5, 6, 2, 4]
for a, b in zip(L, L[1:]):
print(a, b)https://stackoverflow.com/questions/73010561
复制相似问题