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

时间:2017-03-06 06:31:46

标签: python list

我正在尝试将列表cards中的列表playerdeck中的字词分配给变量。这是我尝试使用的代码,但它返回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)

有人可以帮忙吗?

4 个答案:

答案 0 :(得分:1)

您可以尝试:

>>> 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

答案 1 :(得分:0)

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)

答案 2 :(得分:0)

试试这个,它首先遍历卡并检查它们中的哪一个在player_deck中。如果匹配,则将其附加到新的并转到下一张卡。

new = []

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

答案 3 :(得分:0)

这是使用两个循环和单个条件语句的小解决方案(只有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:
...     for card in cards:
...             if card in pd:
...                     print card
... 
Five
Eight
Eight
Four
Ace
Eight
Four

或者,如果您想尝试列表理解:

>>> 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']
>>> result = [card for pd in playerdeck for card in cards if card in pd]
>>> result
['Five', 'Eight', 'Eight', 'Four', 'Ace', 'Eight', 'Four']