I want to make a program that takes strings from a file - file.txt
apple
banana
horse
love
purple
and then joins the first word with every single other one and so on. The result should look like this:
applebanana
applehorse
applelove
applepurple
bananaapple
bananahorse
bananalove
bananapurple
horseapple
etc.
I get that I should probably use the join function, but I don't know how exactly? (If that makes sense, I am super sorry)
I tried also using zip, but couldn't make it word, so I leave it up to the professionals! <3 (I also use python 3) If u need more info I will try to respond as fast as I can! Thank you all!
CodePudding user response:
#say you have a list of words
l = ['apple', 'banana', 'horse', 'love', 'purple']
for i in range(len(l)):
for j in range(len(l)):
if i != j:
print(l[i] l[j])
CodePudding user response:
This is exactly what itertools.product()
does:
from itertools import product
with open(<your_file>) as f:
lst = [line.strip() for line in f]
for i, j in product(lst, repeat=2):
print(i j)
output:
appleapple
applebanana
applehorse
applelove
applepurple
bananaapple
bananabanana
...
CodePudding user response:
words = []
with open(file_name, "r") as fp:
words = [line.replace('\n', '') for line in fp]
for wi in words:
for wj in words:
print(f"{wi}{wj}")