我如何找出字典中分配给键的值的平均值?
How do i find out the average of values in a dictionary which are assigned to a key?
我编写了一些代码,将文本文件中的考试成绩结果添加到 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 = 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
...
详情设置setdefault
文档
因为我没有你的输入数据文件,我无法真正测试它,但这应该会产生类似的东西:
{'Ruan': [22], 'hello': [22, 1], 'kurun': [29]}
在那之后,您的其余代码应该可以正常工作,因为您现在统一拥有整数列表。无论同一玩家的"scores"个数是多少。
不确定所有代码在做什么,但使用 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,您可以在之前的循环中对名称进行分组,使用分数作为键并附加名称来反转逻辑。
您还可以让 statistics 模块处理平均值,将代码替换为:
from statistics import mean
for name,scores in diction1.items():
student_average = mean(scores)
averages_dct[name] = student_average
我编写了一些代码,将文本文件中的考试成绩结果添加到 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 = 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
...
详情设置setdefault
文档
因为我没有你的输入数据文件,我无法真正测试它,但这应该会产生类似的东西:
{'Ruan': [22], 'hello': [22, 1], 'kurun': [29]}
在那之后,您的其余代码应该可以正常工作,因为您现在统一拥有整数列表。无论同一玩家的"scores"个数是多少。
不确定所有代码在做什么,但使用 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,您可以在之前的循环中对名称进行分组,使用分数作为键并附加名称来反转逻辑。
您还可以让 statistics 模块处理平均值,将代码替换为:
from statistics import mean
for name,scores in diction1.items():
student_average = mean(scores)
averages_dct[name] = student_average