简体   繁体   中英

List Comprehension with Not In

What I'm trying to do is a list comprehension but I'm not getting the result I expected. I'm writing a playing card game.

So I start with a list like this, that has 5 cards

card_numbers = [ 13, 4, 13, 11, 14 ]

the numbers represent cards, ie 13 represents a King, so theres a pair of kings in this hand.

I need to find out how many pairs appear in this list. There is 1 pair of kings, so I need a list called pairs that contains a single element, 13, like so:

pairs = [ 13 ]

This is what I'm trying:

pairs = [ number for number in card_numbers if card_numbers.count(number) == 2 and number not in pairs ]

However, this gives me

pairs = [ 13, 13 ]

It's like the not in part isn't registering, I think because I'm trying to refer to the same list I'm creating with the comprehension. What am I doing wrong?

This does quite literally what you need, is this what you're after?

from collections import Counter

card_numbers = [13, 4, 13, 11, 14]
card_counts = Counter(card_numbers)
print([card for card, count in card_counts.items() if count == 2])

Since it's become clear you want cards for all possible counts, something like this is straightforward:

from collections import Counter, defaultdict

card_numbers = [13, 4, 13, 11, 14]
card_counts = defaultdict(list)
for card, count in Counter(card_numbers).items():
    card_counts[count].append(card)
print(card_counts)

Yes, it is because you are trying to refer to the same list you are creating with the comprehension. A solution to this would be to use a for loop.

for number in card_numbers:
    if card_numbers.count(number) == 2 and number not in pairs:
        pairs.append(number)

Try making it a set first, then you don't even need your check (and you save time by not counting duplicates again).

>>> [number for number in set(card_numbers) if card_numbers.count(number) == 2]
[13]

如果您不想导入库(您应该导入),这是一个解决方案:

doubles = [s for s in set(card_numbers) if sum([c == s for c in card_numbers]) == 2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM