首先,你需要正確地通過剝離任何換行符或空格字符閱讀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
你有沒有在你的文本文件一號線2號線和琴絃? – Dark
是的,這是可能的。 –
Python文檔解釋瞭如何讀取文件以及如何拆分一條線,如何在陣列中打開它等。 https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-文件 https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects –