我正在尝试创建一个扑克游戏,我有一个值列表,可以是列表中的Ace到King的任何值(名为" number")。为了确定玩家是否具有"四种类型",程序需要检查值列表中的四个项是否相同。
我不知道如何做到这一点。你会以某种方式使用number[0] == any in number
函数四次,还是完全不同?
答案 0 :(得分: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)
答案 1 :(得分: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