如何合并来自多个文件的多行并将其放入数组

时间:2019-02-15 23:14:31

标签: python python-2.x

我有三个文本文件,每个文件都包含这样的文本

file1.txt
    a1
    a2
    a3

file2.txt
    b1
    b2

file3
    c1
    c2

我需要将它们添加到这样的数组中

[[a1,b1,c1] , [a1,b1,c2] , [a1,b2,c1] , [a1,b2,c2] , [a2,c1,b1] , ....]

我的代码在这里

list1 = []
x = open('../f1.txt')
y = open('../f2.txt')
z = open('../f3.txt')
for a in x:
  for b in y:
    for c in z:
        list1.append((a.strip() , b.strip(), c.stip()))



for w in list1:
  print w

它仅将x中的第一行与y中的第一行与z中的所有行组合在一起

2 个答案:

答案 0 :(得分:1)

这是一种使用combinations模块中的chainitertools解决问题的方法:

from itertools import combinations, chain


def read_from_files(files):
    """Read all the files"""
    for _file in files:
        with open(_file, 'r') as f:
            # remove `\n` from the end of lines
            yield [elm.strip('\n') for elm in f.readlines()]


def get_output(data, n=3):
    """return combinations based on `n`"""
    # chain the data to get a full list of items
    return combinations(chain.from_iterable(data), n)


files = ['file1', 'file2', 'file3']
data = read_from_files(files)
output = list(get_output(data))
print(output)

输出:

[('a1', 'a2', 'a3'), ('a1', 'a2', 'b1'), ('a1', 'a2', 'b2'), ('a1', 'a2', 'b3'), ('a1', 'a2', 'c1'), ('a1', 'a2', 'c2'), ('a1', 'a3', 'b1'), ('a1', 'a3', 'b2'),
...

('b1', 'b2', 'c2'), ('b1', 'b3', 'c1'), ('b1', 'b3', 'c2'), ('b1', 'c1', 'c2'), ('b2', 'b3', 'c1'), ('b2', 'b3', 'c2'), ('b2', 'c1', 'c2'), ('b3', 'c1', 'c2')]

答案 1 :(得分:0)

当迭代File对象时,只能对其进行一次迭代。 读取z的3行时,y for循环转到f2中的下一行。但是,迭代结束了,因为f3中没有其他行可以读取。

一种解决方案是在所有迭代中重新打开文件,但这不是很性感。我建议直接在开始通话中阅读这三个文件。

我的版本:

list1 = []
lines = []
for file in ['f1', 'f2', 'f3']:
    with open(file) as f:
        lines.append(f.readlines())
for xline in lines[0]:
    for yline in lines[1]:
        for zline in lines[2]:
            list1.append((xline.strip(), yline.strip(), zline.strip()))