Python 如何组合多个文件中的多行并将它们放入一个数组

Python 如何组合多个文件中的多行并将它们放入一个数组,python,python-2.x,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] , ....] 我需要将它们添加到这样的数组中 file1.txt a1 a2 a3 file2.txt b1 b2 file

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

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] , ....]
我需要将它们添加到这样的数组中

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中的所有行组合起来

以下是一种使用
组合和
itertools
模块解决问题的方法:

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')]

迭代文件对象时,只能对其迭代一次。 读取
z
的3行时,for循环的
y
转到
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()))

到目前为止,你尝试了什么?如果你搜索短语“Python文件输入”和“Python itertools组合”,你会找到比我们在这里的答案更好的解释它的资源。我正在更新帖子并设置我在我的案例中编写的代码…非常感谢,我提供了Chiheb Nexus的解决方案。