![](/img/trans.png)
[英]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.