-3

我有一个包含数字列表的文本文件。在这种情况下,我想计算每三个数字的平均值。有什么想法吗?之前谢谢

文本文件中的数字示例:

5
7
3
10
12
6

我想要的输出:

5
9
4

4 回答 4

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])
于 2013-03-23T23:23:24.550 回答
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.
于 2013-03-23T21:54:46.650 回答
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
于 2013-03-23T21:50:28.063 回答
0

这可以通过将文本文件的行保存到列表中来解决。您还应该使用 csv 模块,可以在此处查看 import csv

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

然后,它应该可以获取 allRows 列表,将值相加,然后除以 allRows 的长度。这个模块我不太了解,所以这个答案可能比我解释得更好。

于 2013-03-23T21:48:22.913 回答