2013-03-23 246 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])