繁体   English   中英

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

[英]Saving output of a function to a text file

我有一个函数,可以将多个列表中的项目合并在一起。 因此,如果我有列表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()函数写入文本文件不会执行任何操作。 用return代替print不能正确运行排列。...有关如何将所有排列正确打印到文本文件的任何提示?

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

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

传递文件对象作为参数,并使用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