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

问题描述 投票:1回答:2

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

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

python python-2.x
2个回答
0
投票

迭代File对象时,只能迭代一次。当读取3行z时,y for loop进入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()))

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')]
© www.soinside.com 2019 - 2024. All rights reserved.