为什么我的索引代码在列表中找不到该项?

2024-10-01 04:55:48 发布

您现在位置:Python中文网/ 问答频道 /正文

使用for循环和append方法创建的列表出现索引函数错误

我是个新手,所以我不能理解这个问题

from random import shuffle
class Cards:
    suits = [ 'Spades' , 'Hearts' , 'Diamonds' , 'Clubs' ]
    faces = [ '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '10' , 'Jack' , 
              'Queen' , 'King' , 'Ace' ]   
    def __init__ ( self , suit , face):
        '''suit and value should be integers'''
        self.suit = suit
        self.face = face
    def __repr__(self):
        return ('{} of {}').format(self.faces[self.face]
                ,self.suits[self.suit])
class Deck:
    def __init__(self):
        self.deckoc = []
        self.shufdoc = []
        for x in range (4):
            for y in range (13):
                self.deckoc.append(Cards(x,y))
                self.shufdoc.append(Cards(x,y))      
        shuffle (self.shufdoc)    
while True:
    newhand = Deck()    
    c1 = (newhand.shufdoc.pop())
    c2 = (newhand.shufdoc.pop())
    print (c1,c2)
    print (newhand.deckoc.index(c1))    
    print (newhand.shufdoc)
    print (newhand.deckoc) 
    a = input('asd?')
    if a == 'q':
        break

我希望代码也打印索引号,但它会出现“不在列表中”错误


Tags: self列表fordef错误facecardsprint
2条回答

您正在为每个卡创建两个独立的Card实例。因此in无法在另一个列表中找到一个列表的实例

只需复制列表:

class Deck:
    def __init__(self):
        self.deckoc = []
        self.shufdoc = []
        for x in range (4):
            for y in range (13):
                self.deckoc.append(Cards(x,y))
        self.shufdoc = list(self.deckoc)
        shuffle(self.shufdoc)    

有关您的逻辑问题,请参阅@Daniel的答案。但我建议你重做你的逻辑。没有理由有复杂的指数或两个不同的甲板

以下是我如何在自己制作的扑克程序中创建牌组:

for _ in range(decks_):
    for val in (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14):
        for suit in ("Hearts", "Spades", "Clubs", "Diamonds"):
            self.cards.append(Card(val, suit))

    if self.shuffle_cards:
            shuffle(self.cards)

您没有多个组,因此不需要第一个for循环,除非您希望在将来添加更多组

您可以这样定义命名词典:

value_names = {2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine',
               10: 'Ten', 11: 'Jack', 12: 'Queen', 13: 'King', 14: 'Ace'}

suit_names = {"Hearts": '♥', "Spades": '♠', "Clubs": '♣', "Diamonds": '♦'}

然后将您的卡类定义为:

class Card:
    """A class containing the value and suit for each card"""
    def __init__(self, value, suit):
        self.value = value
        self.suit = suit
        self.vname = value_names[value]
        self.sname = suit_names[suit]

相关问题 更多 >