尽管给出了输出,Python代码仍给出了IndexError

时间:2019-07-07 21:54:02

标签: python-3.x index-error

我在Python代码中得到了IndexError

这是代码:

n = int(input())  
cardp_1 = [input() for i in range(n)]
warcount=0
m = int(input())  
cardp_2 = [input() for j in range(m)]
while cardp_1 != [] or cardp_2 != []:
    # print(cardp_1[0],cardp_2[0])
    c1 = cardp_1[0]
    c2 = cardp_2[0]
    res = stronger(c1, c2)
    if res == 1:
        cardp_1.remove(c1)
        cardp_2.remove(c2)
        cardp_1.append(c1)
        cardp_1.append(c2)
    elif res == 2:
        cardp_1.remove(c1)
        cardp_2.remove(c2)
        cardp_2.append(c1)
        cardp_2.append(c2)
if cardp_2 == []:
    print('2', warcount)
else:
    print('1', warcount)

该程序应该可以正常运行,而是给出IndexError

Traceback (most recent call last):   File
"C:/Users/risha/PycharmProjects/HelloWorld/cards_war.py", line 9, in
<module>
    c2 = cardp_2[0] IndexError: list index out of range

奇怪的是,我尝试在while循环中打印c1c2的值,并且每次迭代都会打印出来。

1 个答案:

答案 0 :(得分:1)

此循环:

while cardp_1 != [] or cardp_2 != []:

只要只要 数组不为空,就保持迭代,但是您要做的第一件事就是从 both 中获取第一个元素。如果一个数组为空,则将遇到您描述的错误。