Python:如何确定列表中特定数量的项是否相同?
我正在尝试创建一个扑克游戏,我有一个列表,列表中的值可以是从王牌到王牌的任何值(名为“数字”)。为了确定玩家是否有“一类四项”,程序需要检查值列表中的四项是否相同。 我不知道怎么做。您是否会四次使用Python:如何确定列表中特定数量的项是否相同?,python,arrays,list,poker,Python,Arrays,List,Poker,我正在尝试创建一个扑克游戏,我有一个列表,列表中的值可以是从王牌到王牌的任何值(名为“数字”)。为了确定玩家是否有“一类四项”,程序需要检查值列表中的四项是否相同。 我不知道怎么做。您是否会四次使用number[0]==any in number函数,还是完全不同?假设您的number变量是一个包含5个元素(五张卡)的列表,您可能可以尝试以下操作: from collections import Counter numbers = [1,4,5,5,6] c = Counter(numbers)
number[0]==any in number
函数,还是完全不同?假设您的number变量是一个包含5个元素(五张卡)的列表,您可能可以尝试以下操作:
from collections import Counter
numbers = [1,4,5,5,6]
c = Counter(numbers)
这充分利用了以下因素:)
拥有计数器后,您可以通过执行以下操作检查最常见的发生次数:
# 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)
您还可以将这些计数存储在中,并检查最大出现次数是否等于您的特定项数:
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
更好的是,如答案所示:
你应该表现出诚实的尝试,并说明为什么它不符合你的要求。所以,这不是一个免费的代码编写服务…用字典把名字翻译成数字,这使得比较更容易。将一张卡片分为价值卡和套装卡,并成对保存。我发现numpy很容易简化比较。“一种类型的四张牌”是一种手牌游戏,其中有四张牌具有相同的值,例如四张2或四张a。在评估扑克手牌时,最好先按等级对手牌进行排序。这使得很多手工检查变得容易多了。
from collections import Counter
from operator import itemgetter
def check_cards(hand, count):
return max(Counter(map(itemgetter(0), hand)).values()) == count