如何检查列表中某项的频率,然后如果该项的频率为4,则删除所有匹配项?
上下文:
尝试用python创建围棋游戏,我需要能够检查玩家的手牌是否具有四个匹配数字,如果玩家的手牌确实存在,那么我需要删除所有四个匹配项,并在其中将得分提高{ {1}}
输入
char ch = ptr[3]; // 'd' in "World"
输出
1
玩家的手是一个数字列表。
这是游戏文件: ''' https://github.com/StarSpace-Interactive/GoFish/tree/master/GoFish
答案 0 :(得分:1)
这是一个解决方案:
from collections import Counter
score = 0
hand = [1,2,4,3,5,6,1,1,1]
counts = Counter(hand)
for num, count in counts.items():
if count >= 4:
hand = list(filter((num).__ne__, hand))
score += 1
print(hand)
print(score)
输出为:
[2, 4, 3, 5, 6]
1
答案 1 :(得分:0)
from collections import defaultdict
score = 0
hand = [1,2,4,3,5,6,1,1,1] # current hand
# im guessing you are doing this in a loop
d= defaultdict( int )
for card in hand:
d[card] += 1
fourList = []
for key, value in d.items():
if value >= 4:
fourList.append(key)
hand = [n for n in hand if n not in fourList]
score += len(fourList)
print(hand)
print(score)
答案 2 :(得分:0)
您可以通过Counter
来实现自己的目标。例如,
from collections import Counter
mylist = [1,2,4,3,5,6,1,1,1]
counter = Counter(mylist)
然后,counter
是
Counter({
1: 4,
2: 1,
4: 1,
3: 1,
5: 1,
6: 1
})
然后,您可以编写一个python函数来更新得分和计数器。
def update_score(counter, curr_score):
remove_keys = list()
# update score
for key, value in counter.items():
if value >= 4:
curr_score += 1
remove_keys.append(key)
# remove key
for key in remove_keys:
del counter[key]
return counter, curr_score
它将返回新的当前分数和更新的计数器。
答案 3 :(得分:0)
就我个人而言,我发现pandas
value_count
函数比上面建议的numpy.histogram
更用户友好。您可以像这样使用它,假设您的手是一张牌(当然,如果手是系列,则此解决方案会更简单):
import pandas as pd
hand = [1,1,2,3,4,1,1]
cards_count = pd.Series.value_counts(hand)
# count how many times each card appears
score += (cards_count>=4).sum()
# add 1 to score for each card that repeats at least 4 times
hand = [card for card in hand if card not in cards_count.index[cards_count>=4]]
# keeps only cards that did not appear >=4 times