0

我必须测量不同 L 值所花费的时间,所以我想优化我的代码。我必须做的是用直径为 d 的周期点 (x,y,z) 填充一个立方体 (LxLxL),这些点是相同的。到目前为止,这就是我所拥有的:

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

有什么想法或建议吗?提前致谢!

4

1 回答 1

3

可以做几件事:首先,将数据格式化与数据生成分开,其次,使用更清晰的迭代方法。在第一个近似值中,这将是这样的:

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()
于 2012-10-03T06:29:18.200 回答