将值索引回列表中-为什么说它不在列表中?

时间:2019-01-18 23:23:58

标签: python list indexing

我正在尝试使用list.index()函数,但这是说我要索引的对象不在列表中。

我没有做太多尝试,因为说实话,我对python不太了解,但是我尝试过在线搜索问题。

heartsCards = ["Ace of Hearts","Two of Hearts","Three of Hearts","Four of Hearts","Five of Hearts","Six of Hearts","Seven of Hearts","Eight of Hearts","Nine of Hearts","Ten of Hearts","Jack of Hearts","Queen of Hearts","King of Hearts"]
diamondsCards = ["Ace of Diamonds","Two of Diamonds","Three of Diamonds","Four of Diamonds","Five of Diamonds","Six of Diamonds","Seven of Diamonds","Eight of Diamonds","Nine of Diamonds","Ten of Diamonds","Jack of Diamonds","Queen of Diamonds","King of Diamonds"]
clubsCards = ["Ace of Clubs","Two of Clubs","Three of Clubs","Four of Clubs","Five of Clubs","Six of Clubs","Seven of Clubs","Eight of Clubs","Nine of Clubs","Ten of Clubs","Jack of Clubs","Queen of Clubs","King of Clubs"]
spadesCards = ["Ace of Spades","Two of Spades","Three of Spades","Four of Spades","Five of Spades","Six of Spades","Seven of Spades","Eight of Spades","Nine of Spades","Ten of Spades","Jack of Spades","Queen of Spades","King of Spades"]

yourCards = []

cardValue = 0

def pickUp():
    randomNum = random.randint(1,4)

    if randomNum == 1:
        temp = random.choice(heartsCards)
        yourCards.append(temp)
        heartsCards.remove(temp)

    if randomNum == 2:
        temp = random.choice(diamondsCards)
        yourCards.append(temp)
        diamondsCards.remove(temp)

    if randomNum == 3:
        temp = random.choice(clubsCards)
        yourCards.append(temp)
        clubsCards.remove(temp)

    if randomNum == 4:
        temp = random.choice(spadesCards)
        yourCards.append(temp)
        spadesCards.remove(temp)

def cardCount():
    global cardValue

    for card in yourCards:
        if card.count("Hearts") != 0:
            cardValue =+ heartsCards.index(card) + 1

        if card.count("Diamonds") != 0:
            cardValue =+ diamondsCards.index(card) + 1

        if card.count("Clubs") != 0:
            cardValue =+ clubsCards.index(card) + 1

        if card.count("Spades") != 0:
            cardValue =+ spadesCards.index(card) + 1
    return cardValue 

pickUp()
pickUp()

cardCount()

我希望将变量cardValue作为卡的值打印出来。但是我收到此错误:

Traceback (most recent call last):
  File "C:\Users\User\Desktop\Python\Pontoon.py", line 97, in <module>
    cardCount()
  File "C:\Users\User\Desktop\Python\Pontoon.py", line 68, in cardCount
    cardValue =+ diamondsCards.index(card) + 1
ValueError: 'Nine of Diamonds' is not in list

1 个答案:

答案 0 :(得分:-1)

jasonharper在评论中说的有效:

  

pickUp()选择了一张卡片后,该卡片将从诉讼清单中删除。您无法再使用.index()在列表中查找其位置。