【问题标题】:How do I write multiple lists into their own column in a text file?如何将多个列表写入文本文件中自己的列?
【发布时间】:2020-01-30 18:25:34
【问题描述】:

我需要将五个列表制作成一个文本文件,每个列表位于它们自己的列中。到目前为止我有

with open("PR.txt","w") as f:
    PR = [[Velocity], [Angle], [Impact], [y], [Distance]]
    for (x) in zip(PR):
        f.write("{0}\t{1}\t{2}\t{3}\t{4}\n".format(*x))

我想让它写一个文本文件去

Velocity Angle Impact y Distance
Velocity Angle Impact y Distance
Velocity Angle Impact y Distance

等等

我不知道该怎么做。

【问题讨论】:

  • zip 的目的是什么?另外,为什么要将PR 项目存储在列表中?
  • 我真的不知道。我一直在寻找不同的方式并尝试任何事情。我只需要将多个列表制作成具有自己列的文本文件。

标签: python python-3.x list text-files


【解决方案1】:

假设您拥有所有五个长度相同的列表,

with open("PR.txt","w") as f:
 f.write("Velocity\tAngle\tImpact\ty\tDistance") 
 for i in range(0, len(Velocity)):
    # Velocity here is the list
    f.write("{0}\t{1}\t{2}\t{3}\t{4}\n".format(Velocity[i],Angle[i], Impact[i], y[i], Distance[i]))

【讨论】:

  • 这输出了正确的格式,我的所有数字几乎都是正确的,除了少数谢谢。
  • 现在完全可以用了,谢谢。我赞成你的回答,但我没有足够的声誉来表示抱歉。
  • @DominicCasamatta 很高兴它帮助了你:)
【解决方案2】:

您可以使用 *args 将列解压缩为 zip

# test input
pr = [['v 0', 'v 1', 'v 2', 'v 3', 'v 4'], ['10', '11', '12', '13', '14'], ['0', '1', '2', '3', '4'], ['y0', 'y1', 'y2', 'y3', 'y4'], ['dist 0', 'dist 1', 'dist 2', 'dist 3', 'dist 4']]

with open('file.txt', 'w') as fh:
    cols = ['Velocity', 'Angle', 'Impact', 'y', 'Distance']
    fh.write('\t'.join(cols) + '\n')

    # here is where you unpack everything
    for row in zip(*pr):
        fh.write('\t'.join(row) + '\n')

哪些输出

Velocity    Angle   Impact  y   Distance
v 0         10      0       y0  dist 0
v 1         11      1       y1  dist 1
v 2         12      2       y2  dist 2
v 3         13      3       y3  dist 3
v 4         14      4       y4  dist 4

【讨论】:

    猜你喜欢
    • 2020-04-20
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多