Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
条目和,Python_Python - Fatal编程技术网

条目和,Python

条目和,Python,python,Python,可能重复: 我这里有一个小问题,我试图总结来自多个文件(50个)的条目,每个文件包含3列。例如,使用前3个文件:file1.txt、file2.txt、file3.txt,如下所示: file1.txt: 2 3 4 1 5 6 5 4 7 file2.txt: 1 2 1 2 3 2 4 3 1 file3.txt: 6 1 1 1 3 0 3 4 5 所以我的问题是,如何将50个文件中第一列、第二列和第三列的所有条目相加,得到一个如下所示的文件: output.txt: 9 6 6

可能重复:

我这里有一个小问题,我试图总结来自多个文件(50个)的条目,每个文件包含3列。例如,使用前3个文件:file1.txt、file2.txt、file3.txt,如下所示:

file1.txt:

2 3 4
1 5 6
5 4 7
file2.txt:

1 2 1
2 3 2
4 3 1
file3.txt:

6 1 1
1 3 0
3 4 5
所以我的问题是,如何将50个文件中第一列、第二列和第三列的所有条目相加,得到一个如下所示的文件:

output.txt:

9 6 6
4 11 8
12 11 13
我已经读入了50个文件并附加了它们,但是我在一个接一个地求和条目时遇到了困难

所以我做到了:

for p in range(50):
    locals()['first_col%d' % p] = []
    locals()['second_col%d' % p] = []
    locals()['third_col%d' % i] = []

for i in range(1,50):
    f = open("file"+str(i)+".txt","r")
    for line in f:
        locals()['fist_col%d' % i].append(float(line.split()[0]))
        locals()['second_col%d' % i].append(float(line.split()[1]))
        locals()['third_col%d' % i].append(float(line.split()[2]))

f.close()

我正在想办法把它放在一个循环中,它将读取所有的
第一列
第一列
第一列2
第一列3
,等等),
第二列
第三列
,并对条目进行汇总。

我有一个解决方案,可以对每个文件进行汇总,使用空值初始化容器后:

>>> import os
>>> def sum_files(path):
    result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
    for fil in os.listdir(path):
        full_path = os.path.join(path, fil)
        for line_nb, line in enumerate(open(full_path)):
            numbers = line.split()
            for col_nb, nb in enumerate(numbers):
                result[line_nb][col_nb] += int(nb)
    return result

>>> sum_files(path)
[[9, 6, 6], [4, 11, 8], [12, 11, 13]]

这是您的代码片段

try:
    output_matrix=[[0,0,0],[0,0,0],[0,0,0]]
    for i in range (1,51):
        try:        
            f = open("file"+str(i)+".txt","r")
        except IOError, e:
            continue
        if not f:
            continue
        counter=0
        for line in f:
            row=line.split()
            for row_item in range(0,len(row)):
                output_matrix[counter][row_item]=output_matrix[counter][row_item]+int(row[row_item])
            counter=counter+1
    f = open("Output.txt","w")
    for i in range (0,len(output_matrix)):
        for j in range (0,len(output_matrix[i])):
            f.write(str(output_matrix[i][j]) + ' ')
        f.write('\n')
    f.close()
except Exception,e:
    print str(e)

< P> >可以使用<代码> GOLB与文件名模式匹配,然后明智地使用<代码> zip 和滥用>代码>文字> EVA/<代码>(可能要考虑一个生成器来转换为<代码> int >代码> -NB-这期望每个文件的列数和行数相同,否则将发生截断:

from glob import glob
from ast import literal_eval

filenames = glob('/home/jon/file*.txt')
files = [open(filename) for filename in filenames]
for rows in zip(*files):
    nums = [literal_eval(row.replace(' ', ',')) for row in rows]
    print map(sum, zip(*nums))

[9, 6, 6]
[4, 11, 8]
[12, 11, 13]

我支持
literal\u eval
滥用——我认为
tuple(int(x)表示行中的x.split(','))
在这里要好得多(例如,对额外的空格不太敏感)。为什么要问两次完全相同的问题努力让第一个问题对回答者更有吸引力。