Python:如何将列表列表写入文本文件?

Mas*_*s17 2 python list arraylist python-3.x

我有一个列表列表如下:

list_of_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] 
Run Code Online (Sandbox Code Playgroud)

我想file.txt用下面的格式把它写下来。

1 2 3
4 5 6
7 8 9
10 11 12
Run Code Online (Sandbox Code Playgroud)

请注意,逗号括号不在file.txt. 我试图压平list_of_list并写入,file.txt但得到以下输出:

1
2
3
etc.
Run Code Online (Sandbox Code Playgroud)

Ed *_*ard 5

尝试这个:

lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

text = '\n'.join([' '.join([str(j) for j in i]) for i in lst])

with open("file.txt", "w") as file:
    file.write(text)

Run Code Online (Sandbox Code Playgroud)

file.txt

1 2 3
4 5 6
7 8 9
10 11 12
Run Code Online (Sandbox Code Playgroud)

  • 好的答案,使用单个循环而不是在`join`中创建2个不必要的列表可以更有效:`with open('file.txt', 'w') as f: for inside_list in list_of_list: f.write (' '.join(map(str, inner_list)) + '\n')` (4认同)

Ste*_*ann 5

with open('file.txt', 'w') as f:
    for lst in list_of_list:
        print(*lst, file=f)
Run Code Online (Sandbox Code Playgroud)