Python:如何找到列表中特定数量的项是否相同?

2024-06-11 03:37:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个扑克游戏,我有一个列表,其中的值可以是从王牌到王牌的任意值(名为“数字”)。为了确定播放器是否有“一种四个”,程序需要检查值列表中的四个项目是否相同。 我不知道怎么做。你会用number[0] == any in number函数四次吗,还是完全不同?你知道吗


Tags: 项目函数in程序游戏number列表any
2条回答

假设您的number变量是一个包含5个元素(5张卡)的列表,您可以尝试如下操作:

from collections import Counter
numbers = [1,4,5,5,6]
c = Counter(numbers)

这利用了awesome Counter class。:)

一旦有了计数器,您就可以通过执行以下操作来检查最常见的发生次数:

# 0 is to get the most common, 1 is to get the number
max_occurrencies = c.most_common()[0][1]   
# this will result in max_occurrencies=2 (two fives)

如果您还想知道哪张卡如此频繁,您可以使用元组解包一次性获得这两个信息:

card, max_occurrencies = c.most_common()[0]
# this will result in card=5, max_occurrencies=2 (two fives)

您还可以将这些计数存储在^{}中,并检查最大出现次数是否等于您指定的项数:

from collections import defaultdict

def check_cards(hand, count):
    d = defaultdict(int)

    for card in hand:
        rank = card[0]
        d[rank] += 1

    return max(d.values()) == count:

其工作原理如下:

>>> check_cards(['AS', 'AC', 'AD', 'AH', 'QS'], 4) # 4 Aces
True
>>> check_cards(['AS', 'AC', 'AD', '2H', 'QS'], 4) # Only 3 Aces
False

更好的方法是使用^{},如@Gabe's所示,答案是:

from collections import Counter
from operator import itemgetter

def check_cards(hand, count):
    return max(Counter(map(itemgetter(0), hand)).values()) == count

相关问题 更多 >