python-3.x - 如何将单个输出作为单个文件获取
问题描述
我有一个 python 程序,它以随机数作为输入并给出多个单独的输出。运行文件来自这个答案The norm of vector。那么如何修改运行文件以在单独的数据文件(如 1.txt、2.txt....20.txt)中获取每个新的 (x,y,z) 输出
解决方案
保持相同的“Test.py”
import math
class Vector():
def __init__(self,vx,vy,vz):
self.x=vx
self.y=vy
self.z=vz
def norm(self):
xx=self.x**2
yy=self.y**2
zz=self.z**2
return math.sqrt(xx+yy+zz)
添加一个计数器来跟踪要创建的有效输出文件
import math
import numpy as np
from Desktop import Test
def random_range(n, min, max):
return min + np.random.random(n) * (max - min)
file_count = 1
x = random_range(20,2,9)
y = random_range(20,2,9)
z = random_range(20,2,9)
trial_args = np.stack((x, y, z), axis=-1)
for x, y, z in trial_args:
model=Test.Vector(x,y,z)
if model.norm() > 5:
ifp = open(str(file_count) + ".txt", "w")
ifp.write("{}, {}, {} => {}".format(x, y, z, model.norm()))
ifp.close()
file_count += 1
推荐阅读
- configuration - 如何防止 OllyDbg 解释参数?
- javascript - jQuery 抛出 iframe.getElementById 不是函数的错误
- php - 通过解码来整合两个 JSON 结果,然后再次对其进行编码
- javascript - Html 帖子不起作用
- javascript - 重新加载页面/进行回发后如何保留 ActiveTabIndex?
- android - 在软键盘上方放置一个按钮
- python-3.x - 如何使用部分数据?
- reactjs - 反应路由器嵌套路由方法
- c# - WPF - 使用样式更改文本框的滚动条边距
- java - 使用spring条件bean时如何指定单元测试