预期两个参数而不是三个错误

时间:2014-12-09 20:13:55

标签: python dictionary

当我尝试向字典中添加三个项目时,以下代码给出了一个错误:

from collections import deque

#setting up a dictionary so that only the recent most recent values are stored
player_stats = {}
with open("players.dat") as f:
    for line in f:
        classcode, name, score = line.split()
        player_stats.setdefault(classcode, name, deque(maxlen=3))  
        player_stats[name].append(int(score))       

print(player_stats)

我的数据是:

其他玩家

1鲁尼56 等等。我看不出我做错了什么。

2 个答案:

答案 0 :(得分:0)

问题是dicts采用键/值对,因此您需要对额外信息进行分组。以下示例将为每个玩家保留最后3个classcode, score对。我使用defaultdict代替getdefault,因为getdefault会为每次获取创建(并且通常会立即丢弃)双端队列。

from collections import deque, defaultdict

#setting up a dictionary so that only the recent most recent values are stored
player_stats = defaultdict(lambda:deque(maxlen=3))
with open("players.dat") as f:
    for line in f:
        classcode, name, score = line.split()
        player_stats[name].append((classcode, int(score)))      

print(player_stats)

如果你想跟踪每个课程代码的最后3个分数,你可以

from collections import deque, defaultdict

#setting up a dictionary so that only the recent most recent values are stored
player_stats = defaultdict(lambda: defaultdict(lambda: deque(maxlen=3)))
with open("players.dat") as f:
    for line in f:
        classcode, name, score = line.split()
        player_stats[name][classcode].append(int(score))

print(player_stats)

答案 1 :(得分:0)

从评论中可以清楚地看出,名称是每个类,也就是说名称和类代码一起是玩家的唯一标识符。在不同的班级中具有相同名称的人不是同一个人。

因此,您只需跟踪(classcode, name)元组作为player_stats字典的键:

from collections import deque

#setting up a dictionary so that only the recent most recent values are stored
player_stats = {}
with open("players.dat") as f:
    for line in f:
        classcode, name, score = line.split()
        key, score = (classcode, name), int(score)
        player_stats.setdefault(key, deque(maxlen=3)).append(score)

print(player_stats)

这会跟踪每个classcode + name组合的最后三个分数。