代码之家  ›  专栏  ›  技术社区  ›  Sulphuric_Glue

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

  •  1
  • Sulphuric_Glue  · 技术社区  · 6 年前

    我正在尝试创建一个扑克游戏,我有一个列表,列表中的值可以是从Ace到King的任何值(名为“number”)。为了确定玩家是否有“四个一类”,程序需要检查值列表中的四个项目是否相同。 我不知道怎么做。你会用 number[0] == any in number 功能四次,还是完全不同?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Gabe    6 年前

    假设你的 数字 变量是由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)
    
        2
  •  0
  •   RoadRunner    6 年前

    您还可以将这些计数存储在 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