英文:
Writing a multidimensional array to a text file as plain text with python
问题
我有一个类似这样的二维数组:
[["Hello", "World"],
["How", "are", "you?"],
["Bye" "World"]]
我希望它被放入一个文本文件中,如下所示:
Hello World
How are you?
Bye World
我不知道如何做到这一点,请有人帮忙。
英文:
I have a 2D array like this:
[["Hello", "World"],
["How", "are", "you?"],
["Bye" "World"]]
And I would like it to be put into a text file like this:
Hello World
How are you?
Bye World
I have no idea how to do this, please can someone help.
答案1
得分: 1
这是你要的翻译:
这是你要找的吗?
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')
英文:
Is this what you are looking for?
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')
答案2
得分: 1
这是一个更短、更高效的替代方案。
text = [["你好", "世界"],
["你好吗", "?"],
["再见", "世界"]]
with open('test.txt', 'w+') as file:
file.write('\n'.join(map(' '.join, text)))
英文:
This is an alternative that's much shorter and more efficient.
text = [["Hello", "World"],
["How", "are", "you?"],
["Bye", "World"]]
with open('test.txt','w+') as file:
file.write('\n'.join(map(' '.join,text)))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论