用Python将多维数组以纯文本形式写入文本文件

rqqzpn5f  于 2023-05-23  发布在  Python
关注(0)|答案(2)|浏览(177)

我有一个这样的2D数组:

[["Hello", "World"],
 ["How", "are", "you?"],
 ["Bye" "World"]]

我想把它放到一个文本文件里,像这样:

Hello World
How are you?
Bye World

我不知道该怎么做,请有人帮忙。

w46czmvw

w46czmvw1#

这是你要找的吗?

text = [["Hello", "World"],
 ["How", "are", "you?"],
 ["Bye", "World"]]

with open('test.txt', 'w+') as f:
    for outer in text:
        for i, inner in enumerate(outer):
            if i == (len(outer) - 1):
                f.write(f'{inner}')
            else:
                f.write(f'{inner} ')
        f.write('\n')
5q4ezhmt

5q4ezhmt2#

这是一个更短更有效的替代方案。

text = [["Hello", "World"],
 ["How", "are", "you?"],
 ["Bye", "World"]]

with open('test.txt','w+') as file:
    file.write('\n'.join(map(' '.join,text)))

相关问题