简体   繁体   中英

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"). 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?

Supposing that your number variable is a list of 5 elements (five cards) you can probably try something like:

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

This leverages the awesome Counter class . :)

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:

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:

from collections import Counter
from operator import itemgetter

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

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