在显示中输出序列 (Collat​​z) 并作为文本文件

Output of a sequence (Collatz) in Display and as a Textfile

以下代码片段在显示中提供了一个 逗号分隔的 列表:

X = 19     # Start
N = 7      # Length
def f(x, n):
    yield x
    for k in range(0, n):
        if x % 2 == 0:
            x = x / 2
        else:
            x = 3*x + 1
        yield x
print(", ".join(map(str, f(X, N))))
f = file('collatz\N.txt','w')  # gives an empty file and is not named correctly
# f.write(str(f(X,N))  Does not work

我怎样才能将 行分隔的 (如默认情况下一样)作为一个好的命名文本文件,如 collatz19.txt ?

所以显示输出没问题。我也需要文本文件输出,但不知道命令。

您有两种写入文件的选项:

# Write the whole file in one string
with open('collatz\N.txt','w') as fn:
    one_string = "\n".join(map(str, f(X, N)))
    fn.write(one_string + '\n')

或者一次写入文件一行:

with open(r'collatz\Ng.txt','w') as fn:
    gen = f(X, N)
    for line in gen:
        fn.write(str(line)+'\n')