2017-03-06 38 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'] 
相關問題