简体   繁体   中英

Saving output of a function to a text file

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?

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

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)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM