I have three text files each file contain text like this
file1.txt
a1
a2
a3
file2.txt
b1
b2
file3
c1
c2
I need to add them to an array like this
[[a1,b1,c1] , [a1,b1,c2] , [a1,b2,c1] , [a1,b2,c2] , [a2,c1,b1] , ....]
my code here
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
it combine just first line in x with first line in y with all lines in z
Here is an approach to solve your problem using combinations
and chain
from itertools
module:
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)
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')]
When you iterate of a File object, you can only iterate on it once. When the 3 lines of z
are read, the y
for loop goes to the next line in f2
. However the iteration ends since there is no other line to read in f3
.
One solution would be to re-open the files at all iterations, but that's not very sexy. I suggest reading the three files in the opening call directly.
My version :
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()))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.