3 回答

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以將湖泊名稱存儲(chǔ)到字典中,將數(shù)據(jù)存儲(chǔ)在列表中。從那里你只需要fish在這個(gè)例子中循環(huán)你的列表并獲取與id. 最后,只需將weight列表中的求和并除以 的長(zhǎng)度,就可以在下面打印您的平均值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)))
還鼓勵(lì)您使用with open(..)上下文管理器來確保文件在退出時(shí)關(guān)閉。

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個(gè)贊
您不需要使用偏移量來讀取行。此外,您可以使用with來確保完成后文件已關(guān)閉。對(duì)于平均值,您可以將所有數(shù)字放在一個(gè)列表中,然后在最后找到平均值。使用字典將湖 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
有更有效的方法可以做到這一點(diǎn),但這可能是幫助您了解正在發(fā)生的事情的最簡(jiǎn)單的方法。
添加回答
舉報(bào)