gpt4 book ai didi

python - 将 Python itertools 组合移至文件

转载 作者:行者123 更新时间:2023-12-01 07:20:16 26 4
gpt4 key购买 nike

请帮助我将 Python itertools 组合移至文件。我正在使用以下代码:

import itertools
import numpy as np
stuff = ['a', 'b' , 'c' , 'd']
for L in range(0, len(stuff)+1):
for subset in itertools.combinations(stuff, L):
np.savetxt('x.txt', subset, fmt='%s')
print (subset)

它在控制台中显示完整的组合,但在文件中输出只是

a
b
c
d

最佳答案

正如 Paul Rooney 所指出的在他的评论中建议使用文件句柄而不是文件可以解决您的问题:

import itertools
import numpy as np
stuff = ['a', 'b' , 'c' , 'd']
with open("x.txt","wb") as fh:
for L in range(0, len(stuff)+1):
for subset in itertools.combinations(stuff, L):
np.savetxt(fh, subset, fmt="%s", header="-")
print (subset)

我添加了一个 _header: 来分隔文件中的输出:

# -
# -
a
# -
b
# -
c
# -
d
# -
a
b
# -
a
c
# -
a
d
# -
b
c
# -
b
d
# -
...snipp...
# -
a
b
c
d

要获得更简洁的表示:

with open("x.txt","wb") as fh:
for L in range(0, len(stuff)+1):
for subset in itertools.combinations(stuff, L):
l = list(subset)
if l:
format = ("%s,"*len(l)).rstrip(",")
np.savetxt(fh, [l], fmt=format )
print (subset)

接收:

a
b
c
d
a,b
a,c
a,d
b,c
b,d
c,d
a,b,c
a,b,d
a,c,d
b,c,d
a,b,c,d

关于python - 将 Python itertools 组合移至文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57736130/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com