我正在处理一系列游戏,并想知道哪个玩家使用python赢得了大多数游戏。我认为多重(C ++)类型的数据结构可以很容易,因为每个键都是唯一的,但它会计算在dict中推送项目的次数。我在搜索中没有找到任何关于它们的内容后开始自己实现它。
是否有一种更简单的方法可以将dict值设置为添加键的次数而不是像我一样使用列表?
## logFiles is just a list of json files for each game.
winnerList = []
winnerDict = {}
if len(logFiles):
for logFile in logFiles:
jsonData = json.load(open("logs/" + logFile, 'r'))
winnerList.append(str(jsonData[6]['winner']))
for winner in winnerList:
winnerDict[winner] = winnerList.count(winner)
答案 0 :(得分:2)
您正在寻找collections.Counter
:
import collections,json,os.path
winners = collections.Counter()
for logFile in logFiles:
with open(os.path.join("logs", logFile), 'r') as jsonf:
jsonData = json.load(jsonf)
winner = str(jsonData[6]['winner'])
winners[winner] += 1
winnerList = list(winners.keys())
bestPlayers = winners.most_common()
答案 1 :(得分:1)
您可以使用dict.setdefault
winnerDict = {}
if len(logFiles):
for logFile in logFiles:
jsonData = json.load(open("logs/" + logFile, 'r'))
winner = str(jsonData[6]['winner'])
winnerDict.setdefault(winner,0)
winnerDict[winner] += 1