将 Python itertools 组合移动到文件

Move Python itertools combinations to file

请帮助我将 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