3 回答

TA贡献1862条经验 获得超7个赞
您可以将湖泊名称存储到字典中,将数据存储在列表中。从那里你只需要fish在这个例子中循环你的列表并获取与id. 最后,只需将weight列表中的求和并除以 的长度,就可以在下面打印您的平均值fish。
with open('LakeID.txt','r') as l:
lake = l.readlines()
lake = dict([i.rstrip('\n').split() for i in lake])
with open('FishWeights.txt','r') as f:
fish = f.readlines()
fish = [i.rstrip('\n').split() for i in fish]
for i in fish:
print(i[0],lake[i[0]],i[1])
print('The total average is {}'.format(sum(float(i[1]) for i in fish)/len(fish)))
还鼓励您使用with open(..)上下文管理器来确保文件在退出时关闭。

TA贡献1828条经验 获得超13个赞
您不需要使用偏移量来读取行。此外,您可以使用with来确保完成后文件已关闭。对于平均值,您可以将所有数字放在一个列表中,然后在最后找到平均值。使用字典将湖 ID 映射到名称:
lakes = {
1000: "Chemo",
1100: "Greene",
1200: "Toddy"
}
allWeights = []
with open("test.txt", "r") as f:
for line in f:
line = line.strip() # get rid of any whitespace at the end of the line
line = line.split()
lake, weight = line
lake = int(lake)
weight = float(weight)
print(lake, lakes[lake], weight, sep="\t")
allWeights.append(weight)
avg = sum(allWeights) / len(allWeights)
print("The average fish weight is: {0:.2f}".format(avg)) # format to 2 decimal places
输出:
1000 Chemo 4.0
1100 Greene 2.0
1200 Toddy 1.5
1000 Chemo 2.0
1000 Chemo 2.2
1100 Greene 1.9
1200 Toddy 2.8
The average fish weight is: 2.34
有更有效的方法可以做到这一点,但这可能是帮助您了解正在发生的事情的最简单的方法。
添加回答
举报