Python 帮助 |从底部读取文本文件中的数据

标签 python python-2.7 python-3.x

有人可以看看我的程序吗?有一个我无法识别的错误,这让我很困惑。另外,请向我解释问题,以便我了解如何在其他情况下使用该功能和程序。

input_name = input("\nPlease enter students name » ").strip()
datafile = '1.txt'

while open(datafile, 'r') as f:
    data = {}
    for line in f:
        name, value = line.split('=')
        name = name.strip
        value = str(value)
        data.setdefault(name, []).append(value)
else:
    break
avg = {}
for name, scores in data.items():
    last_scores = scores[-3:]
    avg[name] = sum(last_scores) / len(last_scores)

print("\n", input_name,"'s average score is", avg(input_name))

最佳答案

单步

将所有数据读入字典:

data = {}
for line in f:
    name, value = line.split('=')
    name = name.strip()
    value = int(value)
    data.setdefault(name, []).append(value)

数据的内容:

{'Chris': [9, 9],
 'John': [6, 4, 5],
 'Sarah': [4, 7],
 'Tanzil': [4, 4, 10, 5, 3],
 'Tom': [2]}

现在你可以计算平均值了:

last_scores = data['Tanzil'][-3:]
avg = sum(last_scores) / len(last_scores)


>>> avg
6.0

或所有的平均值:

avg = {}
for name, scores in data.items():
    last_scores = scores[-3:]
    avg[name] = sum(last_scores) / len(last_scores)

现在 avg 持有:

{'Chris': 9.0, 'John': 5.0, 'Sarah': 5.5, 'Tanzil': 6.0, 'Tom': 2.0}

显示所有结果:

for name, value in avg.items():
    print(name, value)

打印:

Tanzil 6.0
Chris 9.0
Sarah 5.5
John 5.0
Tom 2.0

或从平均分最高到最低排序:

from operator import  itemgetter

for name, value in sorted(avg.items(), key=itemgetter(1), reverse=True):
        print(name, value)

打印:

Chris 9.0
Tanzil 6.0
Sarah 5.5
John 5.0
Tom 2.0

完整程序

input_name = input("\nPlease enter students name » ").strip()
datafile = '1.txt'

with open(datafile, 'r') as f:
    data = {}
    for line in f:
        name, value = line.split('=')
        name = name.strip()
        value = int(value)
        data.setdefault(name, []).append(value)

avg = {}
for name, scores in data.items():
    last_scores = scores[-3:]
    avg[name] = sum(last_scores) / len(last_scores)

print("\n", input_name,"'s average score is", avg[input_name])

关于Python 帮助 |从底部读取文本文件中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34110140/

相关文章:

python - 带有枚举和 for 循环的代码在第一个字母上给我重复的结果

python - 从另一种语言调用 PyPy 沙箱

VSCode 似乎无法识别 Python3

python - 列表理解结合 2 个列表

python - os.path.exists 在 Windows 上对名为 "CON.csv"的文件给出误报

python - Python 3 中使用 sys 模块的奇怪行为

python - 如何获取 @property getter/setter 的类型?

python - 为什么我不能在我的 bottlepy 应用程序中共享 pymongo 连接实例

python - 在以下 CNN 模型中,全连接层之前的 reshape 是如何工作的?

python - 如何在 python 2.7 中使用 "e"(欧拉数)和电源操作