我在这里需要一些建议。我想创建一个包含足球队的字典,他们拥有的得分数和参加比赛的次数。被分析的每个列表包含一个匹配项,得分最高的团队获胜并获得3分。.用#4行中的computeScores函数计算每个团队的得分数。但是,我也想跟踪每个团队打了多少场比赛。 我可以使用.get语句吗?我的函数返回{'Steinkjer': 0, 'Byåsen': 6, 'Kvik Halden': 3}
,但是我希望它返回{'Steinkjer': [0, 2], 'Byåsen': [6, 3], 'Kvik Halden': [3, 1]}
。预先感谢!
analyzed = [['Steinkjer', 'Byåsen', 3, 5], ['Byåsen', 'Steinkjer', 2, 1], ['Byåsen', 'Kvik Halden', 2, 10]]
def sumTeamValues(analyzed):
D = {}
for match in analyzed:
scores = calculateScores(match[-2],match[-1])
D[match[0]] = D.get(match[0],0) + scores[0]
D[match[1]] = D.get(match[1],0) + scores[1]
return D
答案 0 :(得分:1)
我认为仅凭一个get语句就无法做到这一点。只需将数组存储在字典中即可:
analyzed = [['Steinkjer', 'Byåsen', 3, 5], ['Byåsen', 'Steinkjer', 2, 1], ['Byåsen', 'Kvik Halden', 2, 10]]
def sumTeamValues(analyzed):
D = {}
for match in analyzed:
scores = calculateScores(match[-2],match[-1])
D[match[0]] = [D.get(match[0],[0, 0])[0] + scores[0], D.get(match[0],[0, 0])[1] + 1]
D[match[1]] = [D.get(match[1],[0, 0])[0] + scores[1], D.get(match[1],[0, 0])[1] + 1]
return D
答案 1 :(得分:1)
您可以使用循环来添加新条目,而不必手动添加到字典中。我使用itertools.chain.from_iterable
和Counter
来获取每支球队的比赛频率,并使用列表推导来获得每场比赛的获胜球队。然后,您可以创建一个defaultdict
实例化的列表,以对分数求和并附加游戏频率。所有的库都可以从Python的标准模块库中获得。
import itertools
from collections import Counter, defaultdict
analyzed = [['Steinkjer', 'Byåsen', 3, 5], ['Byåsen', 'Steinkjer', 2, 1], ['Byåsen', 'Kvik Halden', 2, 10]]
freq = Counter(itertools.chain.from_iterable([i[0:2] for i in analyzed]))
winners = [game[int(game[3] - game[2] > 0)] for game in analyzed]
d = defaultdict(list)
for team in winners:
d[team].append(3)
for k,v in freq.items():
d[k] = [sum(d[k])]
d[k].append(v)
print(f'team: {k}\ntotal points:{d[k][0]}\ntotal games:{d[k][1]}\n')
>>
team: Steinkjer
total points:0
total games:2
team: Byåsen
total points:6
total games:3
team: Kvik Halden
total points:3
total games:1
如果说您有
的平局场景analyzed = [['Steinkjer', 'Byåsen', 5, 5], ['Byåsen', 'Steinkjer', 2, 1], ['Byåsen', 'Kvik Halden', 2, 10]]
您可以使用以下内容更改上面的部分,在示例中,为绘制添加1点:
draws = []
for game in analyzed:
if game[3] == game[2]:
draws.append(game[0])
draws.append(game[1])
d = defaultdict(list)
for team in draws:
d[team].append(1)
for team in winners:
d[team].append(3)
for k,v in freq.items():
d[k] = [sum(d[k])]
d[k].append(v)
print(f'team: {k}\ntotal points:{d[k][0]}\ntotal games:{d[k][1]}\n')
>>
team: Steinkjer
total points:1
total games:2
team: Byåsen
total points:4
total games:3
team: Kvik Halden
total points:3
total games:1