在 python 中,是否可以编写一个从.txt文件中读取数据并将该数据转换为列表,进行计算等的程序......
例如,如果您的.txt文件为:
LINE1| 2011 18.5 11.8 19.7 31.6 26.6 37.3 37.4 24.6 34.0 71.3 46.3 28.4 LINE2| 2012 55.2 92.0 87.5 81.0 83.5 79.6 115.1 112.7 115.7 112.7 136.2 127.4
你能计算出每年分配的数字的平均值吗? (注意:我使用的是3.4版本)
答案 0 :(得分:0)
您可以打开文件并读取行,然后拆分它们并将它们转换为列表。你可以使用numpy来计算平均值。希望以下代码有帮助
import numpy as np
text_f = open('file.txt').readlines()
text_f.remove('\n')
arrays= []
for i in text_f:
new = i[6:]
arrays.append(list(map(float, new.split())))
avrgs = {}
for i in arrays:
avrgs[i[0]] = np.mean(i[1:])
avrgs
输出:
{2011.0: 32.291666666666664, 2012.0: 99.88333333333334}
答案 1 :(得分:0)
首先,您需要通过剥离任何换行符或空格字符来正确读取txt文件和格式:
with open(name.txt) as f:
c = f.readlines()
c = [i.strip() for i in c]
现在,
c = ['2011 18.5 11.8 19.7 31.6 26.6 37.3 37.4 24.6 34.0 71.3 46.3 28.4', '2012 55.2 92.0 87.5 81.0 83.5 79.6 115.1 112.7 115.7 112.7 136.2 127.4']
现在,您将每行放入列表中,现在必须将列表中的每个字符串拆分为一个列表并将字符串转换为浮点数:
for i in range(len(c)):
c[i] = map(float, c[i].split(" "))
现在,我们有
c = [[2011.0, 18.5, 11.8, 19.7, 31.6, 26.6, 37.3, 37.4, 24.6, 34.0, 71.3, 46.3, 28.4], [2012.0, 55.2, 92.0, 87.5, 81.0, 83.5, 79.6, 115.1, 112.7, 115.7, 112.7, 136.2, 127.4]]
现在,您知道c
中每个子列表的第一个索引是年份。存储它的最佳数据结构是一个字典,其中键是年份,值是平均值。
year_avg = dict()
for arr in c:
year_avg[arr[0]] = sum(arr[1:]) / len(arr[1:])
你现在有:
year_avg = {2011.0: 32.291666666666664, 2012.0: 99.88333333333334}
供参考,整个代码:
with open("file_name.txt") as f: # Open the file
c = f.readlines() # Read all the files into a variable
c = [i.strip() for i in c] # Format the string properly
for i in range(len(c)):
c[i] = map(float, c[i].split(" ")) # Split each line into list and convert values to floats
year_avg = dict() # Initialize dictionary to store averages
for arr in c: # Iterate over the list
year_avg[arr[0]] = sum(arr[1:]) / len(arr[1:]) # We know that the first index is the year (becomes the key) and find the average from the remaining numbers.
print year_avg