下面是使用兩個循環的小的解決方案和一個條件語句(僅有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']
當然,但在實際的代碼中,playerdeck是來自另一個列表的7個隨機對象的列表。在操作中,我只是簡化了一切。 –
看看答案。 –