简体   繁体   English

列表理解与 Not In

[英]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所以我从一个这样的列表开始,它有 5 张卡片

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.数字代表牌,即13代表一张K,所以这手牌是一对K。

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,如下所示:

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.这就像not in部分没有注册,我想是因为我试图引用我使用理解创建的同一个列表。 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 循环。

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).首先尝试将其set为一set ,然后您甚至不需要支票(并且通过不再计算重复项来节省时间)。

>>> [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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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