即使输出正确,列表索引也会超出范围?

时间:2016-03-22 16:56:58

标签: python python-2.7

我正在制作一个名为" go fish"为了一堂课。

player1Hand = [2, 4, 6, 8, "J", "Q", "K"]
player2Hand = [3, 4, 5, 6, 9, 10, "A"]
player1Guesses = [2, 8, "J", 4, "Q"]
player2Guesses = [6, 9, "A", 5, 3]

基本上有5个回合(总共10个输出)。如果玩家1猜测在玩家2手中,那么我应该输出" HERE' S MY CARD"和" GO FISH"如果卡不在手中,反之亦然。我得到了它的工作,但我一直没有索引错误。

for i in range(20):
    if player1Guesses[i] in player2Hand:
        print ("HERE'S MY CARD")
    else:
        print ("GO FISH")
    if player2Guesses[i] in player1Hand:
        print ("HERE'S MY CARD")
    else:
        print("GO FISH")

我尝试将范围更改为21和19但我仍然得到相同的错误和输出。

GO FISH
HERE'S MY CARD
GO FISH
GO FISH
GO FISH
GO FISH
HERE'S MY CARD
GO FISH
GO FISH
GO FISH
Traceback (most recent call last):
  File "C:\Users\Allen\Dropbox\Computer Science\GoFish.py", line 8, in <module>
    if player1Guesses[i] in player2Hand:
IndexError: list index out of range

我得到了我需要的正确输入但由于某种原因它仍然说索引超出范围。即使程序有效,为什么会出现此错误?我对编码也有点新意,如果你看到任何更简单或更简单的事情,我可以随意使用我的代码!提前谢谢!

- avbirm

3 个答案:

答案 0 :(得分:2)

你的问题在于:

for i in range(20):
    if player1Guesses[i] in player2Hand:

您迭代了20个项目(0到19),但列表中只有5个:

player1Guesses = [2, 8, "J", 4, "Q"]

更改为range(5)不会抛出错误,您也可以检查i是否小于player1Guesses的长度以及您当前正在进行的检查。同样适用于player2Guesses

答案 1 :(得分:1)

检查i是否为有效索引,i的值必须小于列表的长度。

player1Hand = [2, 4, 6, 8, "J", "Q", "K"]
player2Hand = [3, 4, 5, 6, 9, 10, "A"]
player1Guesses = [2, 8, "J", 4, "Q"]
player2Guesses = [6, 9, "A", 5, 3]

for i in range(20):
    if i < len(player1Guesses) and player1Guesses[i] in player2Hand:
        print ("HERE'S MY CARD")
    else:
        print ("GO FISH")
    if i < len(player2Guesses) and player2Guesses[i] in player1Hand:
        print ("HERE'S MY CARD")
    else:
        print("GO FISH")

答案 2 :(得分:1)

迭代列表的实际长度:

length_of_list = len(player1Guesses)
for i in range(length_of_list):
if player1Guesses[i] in player2Hand:
    print ("HERE'S MY CARD")