仅将列表中的某些单词赋给变量

2024-05-14 03:12:17 发布

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

我试图将列表cards中的单词分配给变量。这是我试图使用的代码,但它返回False

playerdeck = ['Five of Spades', 'Eight of Spades',
              'Eight of Clubs', 'Four of Clubs', 'Ace of Spades',
              'Eight of Hearts', 'Four of Diamonds'] 

cards = ['King', 'Queen', 'Jack', 'Ace',
     'Two', 'Three', 'Four', 'Five',
     'Six', 'Seven', 'Eight', 'Nine',
     'Ten']

new = cards in playerdeck
print(new)

有人能帮忙吗


Tags: of代码false列表new单词cardsfour
3条回答

您可以尝试:

>>> playerdeck = ['Five of Spades', 'Eight of Spades',
              'Eight of Clubs', 'Four of Clubs', 'Ace of Spades',
              'Eight of Hearts', 'Four of Diamonds']
>>> cards = ['King', 'Queen', 'Jack', 'Ace',
     'Two', 'Three', 'Four', 'Five',
     'Six', 'Seven', 'Eight', 'Nine',
     'Ten']
>>> 
>>> for pd in playerdeck:
    temp = pd.split(" ")
    for data in temp:
        if data in cards:
            print data


Five
Eight
Eight
Four
Ace
Eight
Four
class Card:
   def __init__(self,value):
       self.value = value
   def __eq__(self,other):          
       return str(other) in self.value
   def __str__(self):
       return self.value
   def __repr__(self):
       return "<Card:'%s'>"%self
   def __hash__(self):
       return hash(self.value.split()[0])

playerdeck = map(Card,['Five of Spades', 'Eight of Spades',
              'Eight of Clubs', 'Four of Clubs', 'Ace of Spades',
              'Eight of Hearts', 'Four of Diamonds'] )

cards = set(['King', 'Queen', 'Jack', 'Ace',
     'Two', 'Three', 'Four', 'Five',
     'Six', 'Seven', 'Eight', 'Nine',
     'Ten'])

print cards.intersection(playerdeck)

试试这个,它首先遍历卡片并检查哪些卡片在玩家牌堆中。如果存在匹配项,它会将其附加到新卡并转到下一张卡

new = []

for card in cards:
    for deck in player_deck:
        if card.lower() in deck.lower():
            new.append(card)
            break

相关问题 更多 >