简体   繁体   English

将功能输出保存到文本文件

[英]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'] : 因此,如果我有列表child0 = ['a', 'b']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. 我无法将var分配给print语句,因为输出每次明显运行时都会改变,并且将permutate()函数写入文本文件不会执行任何操作。 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? 用return代替print不能正确运行排列。...有关如何将所有排列正确打印到文本文件的任何提示?

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() : Python标准库在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. 传递文件对象作为参数,并使用print函数的file参数。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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