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

问题描述 投票:1回答:2

我正在尝试创建一个扑克游戏,我有一个值列表,可以是列表中的Ace到King(名为“数字”)。为了确定玩家是否具有“四种类型”,程序需要检查值列表中的四个项是否相同。我不知道如何做到这一点。你会以某种方式使用number[0] == any in number函数四次,还是完全不同的东西?

python arrays list poker
2个回答
2
投票

假设您的数字变量是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)

0
投票

您还可以将这些计数存储在collections.defaultdict中,并检查最大值是否等于您的特定项目数:

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

更好的是与collections.Counter(),如@Gabe's回答所示:

from collections import Counter
from operator import itemgetter

def check_cards(hand, count):
    return max(Counter(map(itemgetter(0), hand)).values()) == count
© www.soinside.com 2019 - 2024. All rights reserved.