首页 > 解决方案 > 如何将单个输出作为单个文件获取

问题描述

我有一个 python 程序,它以随机数作为输入并给出多个单独的输出。运行文件来自这个答案The norm of vector。那么如何修改运行文件以在单独的数据文件(如 1.txt、2.txt....20.txt)中获取每个新的 (x,y,z) 输出

标签: python-3.x

解决方案


保持相同的“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

推荐阅读