将多维数组以纯文本形式写入文本文件的 Python 示例:

huangapple go评论78阅读模式
英文:

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)))

huangapple
  • 本文由 发表于 2023年5月22日 04:14:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76301759.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定