从 file1 x file2 生成每个单词的笛卡尔积
Generate Cartesian product of each word from file1 x file2
我搜索了很多网站和论坛,但都无法正常工作。我使用 read()、readline() 结合了各种解决方案。我尝试了 while 和 for 循环,但仍然无法弄清楚。
这是任务。我有 2 个扩展名为 txt
的文件。所以文件 1 是 list1.txt
,文件 2 是 list2.txt
list1.txt有
dog
flower
person
list2.txt有
123
456
我要的是下一个。新文档 list3.txt 包含:
dog123
dog456
flower123
flower456
person123
person456
但我无法使用 itertool,因为我无法合并 2 个文件。那是禁止的。
Any1可以帮助寻找解决方案或提供一些建议。
with open('list1.txt', 'r') as l1, open('list2.txt', 'r') as l2, open('list3.txt', 'w') as l3:
for i, l in enumerate(l1):
x = l1.readline()
for j, k in enumerate(l2):
l3.write('%s%s' % (x, l2.readline()))
这个有效:
with open('list1.txt', 'r') as l1, open('list2.txt', 'r') as l2, open('list3.txt', 'w') as l3:
for left_part in l1:
for right_part in l2:
l3.write('%s%s\n' % (left_part.replace("\n",""), right_part.replace("\n","")))
l2.seek(0)
我搜索了很多网站和论坛,但都无法正常工作。我使用 read()、readline() 结合了各种解决方案。我尝试了 while 和 for 循环,但仍然无法弄清楚。
这是任务。我有 2 个扩展名为 txt
的文件。所以文件 1 是 list1.txt
,文件 2 是 list2.txt
list1.txt有
dog
flower
person
list2.txt有
123
456
我要的是下一个。新文档 list3.txt 包含:
dog123
dog456
flower123
flower456
person123
person456
但我无法使用 itertool,因为我无法合并 2 个文件。那是禁止的。 Any1可以帮助寻找解决方案或提供一些建议。
with open('list1.txt', 'r') as l1, open('list2.txt', 'r') as l2, open('list3.txt', 'w') as l3:
for i, l in enumerate(l1):
x = l1.readline()
for j, k in enumerate(l2):
l3.write('%s%s' % (x, l2.readline()))
这个有效:
with open('list1.txt', 'r') as l1, open('list2.txt', 'r') as l2, open('list3.txt', 'w') as l3:
for left_part in l1:
for right_part in l2:
l3.write('%s%s\n' % (left_part.replace("\n",""), right_part.replace("\n","")))
l2.seek(0)