【发布时间】:2021-12-22 13:53:59
【问题描述】:
我正在尝试为稍后要加载到 C++ 中的文本文件创建特定的输出模式。 我用 Python 编写了一个文件,它在一个圆圈中创建随机坐标和运动值。 输出应该有输出:
Place_1 Place_2 Place_3 Movement_1 Movement_2 Movement_3\n
Place_1 Place_2 Place_3 Movement_1 Movement_2 Movement_3\n
Place_1 Place_2 Place_3 Movement_1 Movement_2 Movement_3
代码是使用是
import numpy as np
file = open('log.txt', 'a')
def f(n, center, radius, ecc):
pos = np.zeros((n,6))
r = ecc * radius
for i in range(n):
while 1:
x_1 = -1 + 2 * np.random.rand(1)
x_2 = -1 + 2 * np.random.rand(1)
if (x_1*x_1 + x_2*x_2)<1 :
pos[i,0] = center[0] + r * 2 * x_1 * np.sqrt(1 - x_1*x_1 - x_2*x_2)
pos[i,1] = center[1] + r * 2 * x_2 * np.sqrt(1 - x_1*x_1 - x_2*x_2)
pos[i,2] = center[2] + r * (1 - 2 * (x_1*x_1 + x_2*x_2))
pos[i,3] = (-1 + 2 * np.random.rand(1))
pos[i,4] = (-1 + 2 * np.random.rand(1))
pos[i,5] = (-1 + 2 * np.random.rand(1))
break
string = str(pos[i,:]).strip('[]').rstrip('\n')
file.write(string)
return
f(10000, np.array((127,127,127)), 92, 0.9)
file.close()
但是,我创建的日志格式非常糟糕。如何获得所需的格式?
【问题讨论】:
-
为什么要使用
str(np.array)将列表转换为字符串?可能你最好使用 python 的f-strings -
使用 f'{pos[i,:]}' 我得到输出 `` [ 2.03736833e+02 1.14369585e+02 1.55421313e+02 -1.34950352e-01 -9.72404614e-01 -2.09317199E-01] [1.49366346C + 02 2.06721909C + 02 1.2.06931669S-02 7.564066692S-02 7.564066692S-02 7.564066692S-02 7.564066698C-02 7.564066692S-01 7.5640666998S-01 7.56406688C-01 7.56406688C-01 7.56406688C-01 7.56406688C-01] 3.73819153992 + 02 5.94674798992-017397899898920 + 02 5.94674799992年第7000 + 02 + 01 3.73394744e-01 -2.16969418e-02 -4.58853325e-01][ 9.16926315e+01 1.45733283e+02 1.99514094e+02 3.65330619 ```
-
遗憾的是,这仍然没有满足必要的格式...
-
您需要适当地格式化列表,而不仅仅是吐出整个内容;正在研究解决方案。
-
幸运的是,我已经从 Tim Roberts 那里得到了解决方案,但仍然感谢您!
标签: python string output write