将函数的输出保存到文本文件

时间:2014-03-15 13:39:59

标签: python

我有一个函数可以将多个列表中的项目置于其中并置换它们。因此,如果我有列表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

我遇到了将输出保存到文本文件中的问题。我不能将var分配给print语句,因为输出在每次运行时都会发生变化,而将permutate()函数写入文本文件则不会。执行返回而不是打印将无法正确运行排列....有关如何正确打印所有排列到文本文件的任何提示?

2 个答案:

答案 0 :(得分:4)

您需要构建一个列表并返回该列表对象:

def permutate():
    result = []
    for i in child0:
        for k in child1:
            result.append((i, k))
    return result

for pair in permutate():
    print(*pair)

您正在做的是创建笛卡儿产品,而不是排列。

Python标准库在itertools.product()

中已经具备了这样做的功能
from itertools import product

list(product(child0, child1))

会生成完全相同的列表:

>>> 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

答案 1 :(得分:0)

将文件对象作为参数传递,并使用file函数的print参数。

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)