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

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

Writing a multidimensional array to a text file as plain text with python

问题

我有一个类似这样的二维数组:

  1. [["Hello", "World"],
  2. ["How", "are", "you?"],
  3. ["Bye" "World"]]

我希望它被放入一个文本文件中,如下所示:

  1. Hello World
  2. How are you?
  3. Bye World

我不知道如何做到这一点,请有人帮忙。

英文:

I have a 2D array like this:

  1. [["Hello", "World"],
  2. ["How", "are", "you?"],
  3. ["Bye" "World"]]

And I would like it to be put into a text file like this:

  1. Hello World
  2. How are you?
  3. Bye World

I have no idea how to do this, please can someone help.

答案1

得分: 1

这是你要的翻译:

  1. 这是你要找的吗?
  2. text = [["Hello", "World"],
  3. ["How", "are", "you?"],
  4. ["Bye", "World"]]
  5. with open('test.txt', 'w+') as f:
  6. for outer in text:
  7. for i, inner in enumerate(outer):
  8. if i == (len(outer) - 1):
  9. f.write(f'{inner}')
  10. else:
  11. f.write(f'{inner} ')
  12. f.write('\n')
英文:

Is this what you are looking for?

  1. text = [["Hello", "World"],
  2. ["How", "are", "you?"],
  3. ["Bye", "World"]]
  4. with open('test.txt', 'w+') as f:
  5. for outer in text:
  6. for i, inner in enumerate(outer):
  7. if i == (len(outer) - 1):
  8. f.write(f'{inner}')
  9. else:
  10. f.write(f'{inner} ')
  11. f.write('\n')

答案2

得分: 1

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

  1. text = [["你好", "世界"],
  2. ["你好吗", "?"],
  3. ["再见", "世界"]]
  4. with open('test.txt', 'w+') as file:
  5. file.write('\n'.join(map(' '.join, text)))
英文:

This is an alternative that's much shorter and more efficient.

  1. text = [["Hello", "World"],
  2. ["How", "are", "you?"],
  3. ["Bye", "World"]]
  4. with open('test.txt','w+') as file:
  5. 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:

确定