Reputation: 23
I have a function that takes the items in multiple lists and permutates them. So if I have the lists child0 = ['a', 'b']
and child1 = ['c', 'd']
:
def permutate():
for i in child0:
for k in child1:
print (i, k)
permutate()
# a c
# a d
# b c
# b d
I'm running into problems with saving the output into a text file. I can't assign a var to the print statement because the output will change every time it runs through obviously, and writing the permutate() function to a text file does nothing. Doing a return instead of print won't run the permutation properly.... any tips on how to print all the permutations to a text file properly?
Upvotes: 1
Views: 363
Reputation: 368894
Pass a file object as an argument, and use file
argument of print
function.
def permutate(f):
for i in child0:
for k in child1:
print(i, k, file=f)
with open('testfile.txt', 'w') as f:
permutate(f)
Upvotes: 0
Reputation: 1121256
You need to build a list and return that list object:
def permutate():
result = []
for i in child0:
for k in child1:
result.append((i, k))
return result
for pair in permutate():
print(*pair)
What you are doing is creating the cartesian product, not the permutations.
The Python standard library has a function to do just this already, in itertools.product()
:
from itertools import product
list(product(child0, child1))
would produce the exact same list:
>>> from itertools import product
>>> child0 = ['a', 'b']
>>> child1 = ['c', 'd']
>>> for pair in product(child0, child1):
... print(*pair)
...
a c
a d
b c
b d
Upvotes: 4