2013-03-23 240 views
-3

我有一個包含數字列表的文本文件。在這種情況下,我想計算每三個數字的平均值。任何想法做到這一點?前文本文件編號從Python中的文本文件計算平均值

例如由於:

5 
7 
3 
10 
12 
6 

輸出,我想:

5 
9 
+0

whathaveyoutried.com – TerryA 2013-03-23 21:46:26

回答

0

這可以通過文本文件的行保存到列表來解決。你也應該通過allRows的長度除以使用CSV模塊,它可以在here 導入CSV被看作

file = open("fileName.txt", 'r') 
reader = csv.reader(file) 
allRows = [row for row in reader] 

然後,它應該工作採取allRows列表,添加值了,。這個模塊我不太清楚,所以this answer可能比我更好地解釋它。

1

假設他們各自在一行:

# text file is myData.txt 
averages = {} # using a dictionary so you can keep track of the starting point 
with open('myData.txt', 'r') as myFile: 
    data = myFile.read().split('\n') # this creates a list of the data 
for index in range(len(data), 3): # step of 3 
    n = float(int(data[index]) + int(data[index+1]) + int(data[index+2]))/3 
    averages[index] = n 

這將引發一個IndexError如果列表是不完全在3塊,所以在try/except塊添加的:

# text file is myData.txt 
averages = {} 
with open('myData.txt', 'r') as myFile: 
    data = myFile.read().split('\n') # this creates a list of the data 
for index in range(len(data), 3): # step of 3 
    try: a = int(data[index]) 
    except (IndexError, TypeError): a = 0 
    try: b = int(data[index+1]) 
    except (IndexError, TypeError): b = 0 
    try: c = int(data[index+2]) 
    except (IndexError, TypeError): c = 0 
    # except (IndexError, TypeError): avoids an error if the end of the list 
    # has been reached or the line is not an integer 
    n = float(a + b + c)/3 
    averages[index] = n 
1

你需要「解析」文本文件並做到這一點,你需要知道它是如何組織以及如何編碼的。我首先給你幾個問題。

  1. 數字是否總是與它們之間存在空格?
  2. 你想在哪裏輸出?打印到控制檯?在新的txt文件中?

你可以OD以下

#read the file 
my_file = open("C:/numbers.txt",'r') 
my_text = my_file.read() 
my_file.close() 

#get a list of numbers from it (in string form) 
my_text_numbers = my_text.split(' ') 

#use list comprehension to get integer...also consider 
#using map function 
my_int_numbers = [int(n) for n in my_text_numbers] 

#now the averaging part I will leave to you, I assume it's 
#the file reading part you needed help with. 
+0

你'.split() '不一定會奏效 - 如果是這樣的話e文件看起來像'2 \ n7 \ n3 \ n ...',並且根本沒有任何空格?不過,my_text.split()應該可以工作。 – DSM 2013-03-23 21:56:04

+0

絕對我同意,這就是爲什麼我問他的數據是否會被空格分隔。在OP的第一篇文章中,數據被空格而不是行分隔。 – patmo141 2013-03-23 23:16:22

1

data.txt

5 
7 
3 
10 
12 
6 

如何使用numpy對其進行處理:

In [4]: import numpy as np 

In [5]: with open('data.txt') as f: 
    data = f.read().split() 
    ...:  

In [6]: data 
Out[6]: ['5', '7', '3', '10', '12', '6'] 

In [7]: a = np.array(map(float, data)) 

In [8]: a 
Out[8]: array([ 5., 7., 3., 10., 12., 6.]) 

In [9]: b = a.reshape([-1,3]) 

In [10]: b 
Out[10]: 
array([[ 5., 7., 3.], 
     [ 10., 12., 6.]]) 

In [11]: b.sum(1)/3 
Out[11]: array([ 5.  , 9.33333333])