【问题标题】:how to store each array in a line [duplicate]如何将每个数组存储在一行中[重复]
【发布时间】:2019-08-13 16:32:10
【问题描述】:

我是python中的一个相当新的东西,我有一个像

这样的数组
[[ 5.2897942e+01  2.2989739e-02  1.9979945e+00  7.9999998e-02]
 [ 5.3750526e+01  1.9291429e-01  2.0269539e+00  0.0000000e+00]
 [ 5.3803116e+01  3.6183926e-01  2.0289137e+00  0.0000000e+00]
 ...
 [ 3.8401384e+00 -1.4381756e+00 -1.7735560e+00  3.4000000e-01]
 [ 3.8257158e+00 -1.4192016e+00 -1.7645701e+00  2.5000000e-01]
 [ 4.0923753e+00 -1.5071962e+00 -1.8955611e+00  0.0000000e+00]]

我需要将每个数组保存为 txt 文件中的一行,例如:

5.2897942e+01  2.2989739e-02  1.9979945e+00  7.9999998e-02
5.3750526e+01  1.9291429e-01  2.0269539e+00  0.0000000e+00
....

请问我该怎么做

【问题讨论】:

  • 使用for循环,有什么问题?
  • 可能是this,也可能是重复的..
  • 我不认为 op 正在使用 numpy..@user77540 你能分享一下你到目前为止尝试过的内容以及遇到问题的地方吗?
  • 我试过了:numpy.savetxt("MyFile.txt", scan, newline=" ") ,现在我怎样才能把每4个元素都保存在txt文件的一行中

标签: python arrays numpy


【解决方案1】:

可能是你想要的。如果不是,请更准确地描述它为什么不能解决您的问题。

array = [[5.2897942e+01, 2.2989739e-02, 1.9979945e+00, 7.9999998e-02],
         [5.3750526e+01, 1.9291429e-01, 2.0269539e+00, 0.0000000e+00],
         [3.8401384e+00, -1.4381756e+00, -1.7735560e+00, 3.4000000e-01],
         [3.8257158e+00, -1.4192016e+00, -1.7645701e+00, 2.5000000e-01]]

with open('/tmp/numbers.txt', 'w') as f:
    for row in array:
        f.write('  '.join('{0:.7e}'.format(n) for n in row) + '\n')

只需将 /tmp/numbers.txt 替换为您选择的文件名即可。

【讨论】:

  • 我收到一个错误 TypeError: 'numpy.int32' object is not iterable
  • 在不了解上下文的情况下,我们无法说出您收到错误消息的原因。您可能在此示例中更改了某些内容。它以前如何?这个例子只是一个例子,不是直接的解决方案。由于您的问题非常模糊,我不得不猜测。我发布了这个例子,而不是问问题。也许它有帮助,也许它会引导你解释为什么它没有。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-12
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
  • 2012-10-02
  • 2018-08-16
  • 2019-02-23
相关资源
最近更新 更多