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

2024-04-20 12:48:38 发布

您现在位置: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

我在将输出保存到文本文件时遇到问题。我不能给print语句分配var,因为每次运行时输出都会发生明显的变化,而将permutate()函数写入文本文件不会起任何作用。用返回代替打印不会正确运行排列。。。。关于如何将所有排列正确地打印到文本文件中有什么提示吗?你知道吗


Tags: 函数in列表forvardef语句print
2条回答

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

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

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

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

您所做的是创建笛卡尔积,而不是排列。你知道吗

Python标准库在^{}中已经有了一个函数:

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

相关问题 更多 >