有效的方式来重写这段代码?

时间:2012-10-03 06:14:13

标签: python performance

我必须通过改变L值来测量所需的时间,因此我想优化我的代码。我必须做的是填充一个立方体框(LxLxL),其直径d的周期点(x,y,z)是相同的。到目前为止,这就是我所拥有的:

L=10
d=2

x,y,z = 0,0,0
counter=0

with open("question1.xyz","w") as f:
    while x<=L-d:
        while y<=L-d:
            while z<=L-d:
                f.write('H ')
                f.write('%f ' %x )
                f.write('%f ' %y )
                f.write('%f\n' %z )
                counter=counter+1
                z=z+d
            z=0
            y=y+d
        z,y=0,0
        x=x+d

然后我必须输出这种格式的文件(.xyz文件):

H 0.000000 0.000000 0.000000
H 0.000000 0.000000 1.000000
H 0.000000 0.000000 2.000000
H 0.000000 0.000000 3.000000
H 0.000000 0.000000 4.000000

有任何想法或建议吗?提前谢谢!

1 个答案:

答案 0 :(得分:3)

可以做几件事:第一,从数据生成中分离数据格式,第二,使用a cleaner iteration approach。在第一个近似中,这将是这样的:

from itertools import product

def iterate_3d(size, step=1):
    """ Generate the data using the standard lib """
    # an iterable range between 0 and `size` with `step`, not including size
    vals = xrange(0, size, step)  

    return product(vals, repeat=3)  # replaces your nested loops


def save(filename, data):    
    """ Format and save the data, which is a sequence of (x, y, z) tuples """
    with open(filename, "w") as f:
        for x, y, z in data:
            f.write("H %f %f %f\n" % (x, y, z))

def main():
    data = iterate_3d(10, 2)
    save("question1.xyz", data)


if __name__=='__main__':
    main()