2017-03-06 54 views
2

我试图将列表playerdeck中的列表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) 

有人可以帮忙吗?

+0

当然,但在实际的代码中,playerdeck是来自另一个列表的7个随机对象的列表。在操作中,我只是简化了一切。 –

+0

看看答案。 –

回答

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

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

new = [] 

for card in cards: 
    for deck in player_deck: 
     if card.lower() in deck.lower(): 
      new.append(card) 
      break 
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 
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'] 
相关问题