Python 将函数输出保存到文本文件
我有一个函数,可以获取多个列表中的项并对它们进行排列。因此,如果我有列表Python 将函数输出保存到文本文件,python,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,因为每次执行print语句时,输
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,因为每次执行print语句时,输出都会发生变化,而将permutate()函数写入文本文件不会产生任何效果。使用返回而不是打印将无法正确运行排列。。。。有关如何将所有排列正确打印到文本文件的提示?您需要构建一个列表并返回该列表对象:
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
>>> child0 = ['a', 'b']
>>> child1 = ['c', 'd']
>>> for pair in product(child0, child1):
... print(*pair)
...
a c
a d
b c
b d
您需要构建一个列表并返回该列表对象:
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
>>> 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)
将文件对象作为参数传递,并使用
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)
从permute函数中而不是(或)打印函数中打印到文件。从permute函数中而不是(或)打印函数中打印到文件。+1:对于笛卡尔积。许多人对置换这个术语的用法感到困惑,因为它只是一个真正的有序组合。许多人对术语排列的用法感到困惑,因为它实际上是有序组合。