So I am creating a card game in python. For the part of the game I an currently working on, I need to check an array of playing cards to see if there are any pairs. A pair is considered two cards with the same value and color. For example, king of hearts and king of diamonds are a pair, but king of hearts and king of clubs aren't.
I need to return a new list with all of the pairs removed.
Suppose we have
list = ['9♠', '5♠', 'K♢', 'A♣', 'K♣', 'K♡', '2♠', 'Q♠', 'K♠', 'Q♢', 'J♠', 'A♡', '4♣', '5♣', '7♡', 'A♠', '10♣', 'Q♡', '8♡', '9♢', '10♢', 'J♡', '10♡', 'J♣', '3♡']
The result should be:
list without pairs = ['10♣', '2♠', '3♡', '4♣', '7♡', '8♡', '9♠', '9♢', 'A♣', 'A♡', 'A♠', 'J♠', 'J♡', 'J♣', 'K♢', 'K♣', 'K♡', 'K♠', 'Q♠']
I currently have this code:
import random
result=[]
for i in range(len(l)):
if '♣' in l[i]:
pass
elif '♠' in l[i]:
pass
elif '♡' in l[i]:
pass
elif '♢' in l[i]:
pass
random.shuffle(result)
return result
cards_list = [
"9♠",
"5♠",
"K♢",
"A♣",
"K♣",
"K♡",
"2♠",
"Q♠",
"K♠",
"Q♢",
"J♠",
"A♡",
"4♣",
"5♣",
"7♡",
"A♠",
"10♣",
"Q♡",
"8♡",
"9♢",
"10♢",
"J♡",
"10♡",
"J♣",
"3♡",
]
SAME_COLORS = {"♢": "♡", "♡": "♢", "♠": "♣", "♣": "♠"}
list_without_pairs = []
for card in cards_list:
if card[:-1] + SAME_COLORS[card[-1]] in cards_list:
continue
else:
list_without_pairs.append(card)
print(list_without_pairs)
Output:
['9♠', '2♠', 'Q♠', 'A♡', '4♣', '7♡', '10♣', '8♡', '9♢', 'J♡', '3♡']
This work exactly the same but could be a little bit more confuse:
list_without_pairs = [card for card in cards_list if card[:-1] + SAME_COLORS[card[-1]] not in cards_list]