猿问

Python文件读取问题,可能的infile循环?

问题如下;“编写一个 Python 程序来读取包含湖泊和鱼类数据的文件,并以表格格式设置报告湖泊标识号、湖泊名称和鱼类重量(使用带格式的字符串区域)。该程序应计算平均鱼类重量报道。”


湖泊识别;


1000 Chemo

1100 Greene

1200 Toddy

我必须阅读的文件“FishWeights.txt”包含以下数据;


1000 4.0

1100 2.0

1200 1.5

1000 2.0

1000 2.2

1100 1.9

1200 2.8

我的代码;


f = open("fishweights.txt")

print(f.read(4), "Chemo", f.readline(4))

print(f.read(5), "Greene", f.read(5))

print(f.read(4), "Toddy", f.read(5))

print(f.read(5), "Chemo", f.read(4))

print(f.read(5), "Chemo", f.read(4))

print(f.read(5), "Greene", f.read(4))

print(f.read(5), "Toddy", f.read(4))

我收到的输出是;


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 

这是正确的,因为我必须显示湖的 ID 号、名称和每个湖的鱼重。但我需要能够进行计算,在最后平均所有鱼的重量。输出应该整齐地格式化,如下所示;


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

感谢任何帮助,这里只是一个初学者,寻求帮助以全面了解该主题。谢谢!


守着一只汪
浏览 244回答 3
3回答

牧羊人nacy

您可以将湖泊名称存储到字典中,将数据存储在列表中。从那里你只需要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(..)上下文管理器来确保文件在退出时关闭。

慕田峪7331174

您不需要使用偏移量来读取行。此外,您可以使用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.01100    Greene  2.01200    Toddy   1.51000    Chemo   2.01000    Chemo   2.21100    Greene  1.91200    Toddy   2.8The average fish weight is: 2.34有更有效的方法可以做到这一点,但这可能是帮助您了解正在发生的事情的最简单的方法。
随时随地看视频慕课网APP

相关分类

Python
我要回答