[英]How to find identical index between columns that has different number of items in python?
[英]Python: How to find whether a specific number of items in a list are identical?
我正在尝试创建一个扑克游戏,并且在列表中有一个值列表,该值可以是从Ace到King的任何东西(称为“数字”)。 为了确定玩家是否具有“四种”,程序需要检查值列表中的四个项目是否相同。 我不知道该怎么做。 您会以某种方式number[0] == any in number
函数中使用number[0] == any in number
四次,还是完全不同?
假设您的数字变量是5个元素(五张卡片)的列表,则可以尝试执行以下操作:
from collections import Counter
numbers = [1,4,5,5,6]
c = Counter(numbers)
这利用了很棒的Counter类 。 :)
有了计数器后,您可以通过执行以下操作检查最常见的发生次数:
# 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)
您还可以将这些计数存储在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的答案所示:
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.