简体   繁体   English

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

[英]Python: How to find whether a specific number of items in a list are identical?

I am attempting to create a poker game, and I have a list of values which can be anything from Ace to King in a list (named "number"). 我正在尝试创建一个扑克游戏,并且在列表中有一个值列表,该值可以是从Ace到King的任何东西(称为“数字”)。 In order to determine whether or not the player has a "Four of a Kind", the program needs to check if four items in the list of values are identical. 为了确定玩家是否具有“四种”,程序需要检查值列表中的四个项目是否相同。 I have no clue how to do this. 我不知道该怎么做。 Would you somehow use the number[0] == any in number function four times, or is it something completely different? 您会以某种方式number[0] == any in number函数中使用number[0] == any in number四次,还是完全不同?

Supposing that your number variable is a list of 5 elements (five cards) you can probably try something like: 假设您的数字变量是5个元素(五张卡片)的列表,则可以尝试执行以下操作:

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

This leverages the awesome Counter class . 这利用了很棒的Counter类 :) :)

Once you have the counter you can check for what is the number of most common occurencies by doing: 有了计数器后,您可以通过执行以下操作检查最常见的发生次数:

# 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)

If you also want to know which one is the card that is so frequent you can get both information in one go using tuple unpacking: 如果您还想知道哪张卡是如此频繁,则可以使用元组拆包一次性获得两种信息:

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

You an also store these counts in a collections.defaultdict , and check if the max occurrence is equal to your specific number of items: 您还可以将这些计数存储在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:

Which works as follows: 其工作原理如下:

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

Even better is with collections.Counter() , as shown in @Gabe's answer: 更好的是使用collections.Counter() ,如@Gabe的答案所示:

from collections import Counter
from operator import itemgetter

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

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

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