So i have my hand of cards that i randomly dealt from a deck but i need to remove the duplicate numbers in my hand. I have no idea where to start.
this is an example of what my hand would look like before removing the pairs:
l=['6♠', '6♣', '7♢', '10♣', '8♣', '2♣', '9♠', '8♢', '7♠', 'K♢', '9♡', 'Q♡', '10♢', '2♠', 'K♡', '2♢', '3♢', 'Q♢', '6♡', '4♣', 'A♡', '4♡', 'A♠', 'A♣', 'J♣', 'Q♠']
and this is what i've tried:
no_pairs=[]
l.sort()
for i in range(len(l)):
for j in (i 1, len(l)):
if i[-2] not in j:
no_pairs.append(i)
when i do this, it keeps saying
TypeError: 'int' object is not subscriptable
CodePudding user response:
Check for the occurrence of each element in the list, and append only if occurs once.
l=['6♠', '6♣', '7♢', '10♣', '8♣', '2♣', '9♠', '8♢', '7♠', 'K♢', '9♡', 'Q♡', '10♢', '2♠', 'K♡', '2♢', '3♢', 'Q♢', '6♡', '4♣', 'A♡', '4♡', 'A♠', 'A♣', 'J♣', 'Q♠']
no_pairs=[]
for i in set(l):
if l.count(i)==1:
no_pairs.append(i)
CodePudding user response:
Get first character of items with item[0]
, then check it is a number with num.isdigit()
method and add it to no_pairs
list.
l=['6♠', '6♣', '7♢', '10♣', '8♣', '2♣', '9♠', '8♢', '7♠', 'K♢', '9♡', 'Q♡', '10♢', '2♠', 'K♡', '2♢', '3♢', 'Q♢', '6♡', '4♣', 'A♡', '4♡', 'A♠', 'A♣', 'J♣', 'Q♠']
no_pairs = []
for item in l:
num = item[0]
if num.isdigit():
num = int(num)
no_pairs.append(int(num))
print(no_pairs)
#output :
[6, 6, 7, 1, 8, 2, 9, 8, 7, 9, 1, 2, 2, 3, 6, 4, 4]
CodePudding user response:
Strip the final character when iterating through the list of strings.
If you're just looking for the number, ignoring the suit, then you just need to strip the suit from the number before comparing it to an array of the numbers you've already sorted, and then adding both the stripped value to the array of numbers, and the original value to the final output. This should work:
l.sort()
sorted_num = []
final = []
for i in l:
if i[:-1] not in sorted_num:
sorted_num.append(i[:-1])
final.append(i)
When run, this gives the value of final as:
['10♢', '2♠', '3♢', '4♡', '6♠', '7♠', '8♢', '9♠', 'A♠', 'J♣', 'K♡', 'Q♠']
CodePudding user response:
Your i
is an int, you can achieve i[2]
(for the error). Then I really don't know where your code was going, so I didn't try to fix I wrote a new one.
I'd suggest you keep track of the numbers you already added, so that you know if you add the card or not
l = ['6♠', '6♣', '7♢', '10♣', '8♣', '2♣', '9♠', '8♢', '7♠', 'K♢', '9♡', 'Q♡', '10♢',
'2♠', 'K♡', '2♢', '3♢', 'Q♢', '6♡', '4♣', 'A♡', '4♡', 'A♠', 'A♣', 'J♣', 'Q♠']
no_pairs = []
nb_cards = set()
for card in l:
nb_card = card[:-1]
if nb_card not in nb_cards:
nb_cards.add(nb_card)
no_pairs.append(card)
print(no_pairs) # ['6♠', '7♢', '10♣', '8♣', '2♣', '9♠', 'K♢', 'Q♡', '3♢', '4♣', 'A♡', 'J♣']
You can replace the set
by a list
, but that woul dbe just less performant