Python 如何找出字典中分配给键的值的平均值?
我编写了一段代码,将文本文件中的测试分数结果以以下格式添加到python字典中:Python 如何找出字典中分配给键的值的平均值?,python,dictionary,Python,Dictionary,我编写了一段代码,将文本文件中的测试分数结果以以下格式添加到python字典中: {'Ruan': '22', 'hello': [22, 1], 'kurun': '29'} 我想算出每个人的平均分数,这就是我迄今为止所尝试的: while choice == 'av': if schClass == '1': schClass = open("scores1.txt", 'r') li = open("scores1.txt", 'r') data =
{'Ruan': '22', 'hello': [22, 1], 'kurun': '29'}
我想算出每个人的平均分数,这就是我迄今为止所尝试的:
while choice == 'av':
if schClass == '1':
schClass = open("scores1.txt", 'r')
li = open("scores1.txt", 'r')
data = li.read().splitlines()
for li in data:
name = li.split(":")[0]
score = li.split(":")[1]
if name not in diction1:
diction1[name] = score
if name in diction1:
diction1[name] = [int(diction1[name]),int(score)]
print(diction1)
averages_dct = {}
for name in diction1:
student_average = sum((diction1[name])) / len((diction1[name]))
averages_dct.update({name: student_average})
reversed_dct = {averages_dct[k]: [] for k in averages_dct}
for average in reversed_dct:
for name in averages_dct:
if average == averages_dct[name]:
reversed_dct[average].append(name)
for av in sorted(reversed_dct, reverse=True):
print('average: %s, students: %s' % (av, reversed_dct[av]))
这就是错误:
student_average = sum((diction1[name])) / len((diction1[name]))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
我完全理解这意味着什么,不知道如何解决它?在数据结构中混合使用字符串和整数列表是不明智的。你应该试试那样的。这将有助于进一步计算:
while choice == 'av':
if schClass == '1':
schClass = open("scores1.txt", 'r')
li = open("scores1.txt", 'r')
data = li.read().splitlines()
for li in data:
name = li.split(":")[0]
score = li.split(":")[1]
diction1.setdefault(name,[]).append(int(score))
# The following loop should work,
# even if it can be optimized (see Padraic's answer)
for name in diction1:
student_average = sum(diction1[name]) / len(diction1[name])
averages_dct[name] = student_average
...
为详细信息设置的文档
由于我没有您的输入数据文件,我无法真正测试它,但这应该会产生如下结果:
{'Ruan': [22], 'hello': [22, 1], 'kurun': [29]}
在这之后,代码的其余部分应该可以正常工作,因为您现在统一拥有整数列表。无论同一玩家的“分数”是多少。不确定所有代码都在做什么,但使用a键并将所有分数存储在一个列表中会更容易求和和和平均,如果该键不存在,defaultdict将添加名称并追加,如果该键存在,则仅追加每个分数,它比使用dict.setdefault更有效:
from collections import defaultdict
diction1 = defaultdict(list)
averages_dct = {}
student_average = {}
while choice == 'av': #
if schClass == '1': # not sure what this is supposed to do
schClass = open("scores1.txt", 'r')
with open("scores1.txt") as f:
for li in f: # just iterate over the file object
name, score = li.split(":") # split once and unpack
# append score cast as int to the list
diction1[name].append(int(score))
# now average scores for each using calling sum on lists of ints
for name,scores in diction1.items():
student_average = sum(scores) / len(scores)
averages_dct[name] = student_average
我假设您的下一个循环是查找具有相同平均分数的名称,因此我们可以再次使用defaultdict,使用平均值作为键,并附加具有相同平均值的名称:
common_dct = defaultdict(list)
# use items to get the key and value
for name, average in averages_dct.items():
common_dct[averages_dct].append(name)
如果您不想实际使用common_dict,您可以在上一个循环中使用分数作为键并附加名称,对名称进行分组,从而颠倒逻辑
您还可以让模块处理平均值,将代码替换为:
from statistics import mean
for name,scores in diction1.items():
student_average = mean(scores)
averages_dct[name] = student_average
你不能在一个整数上调用sum,所以我怀疑
name,score=li。split(“:”
将起作用,并用defaultdictok cheers@PadraicCunningham替换dict,我该怎么做才能代替sum?noob,添加了一个答案,将删除丢失的不必要代码