重新编写此代码的有效方法? [英] Efficient way to re-write this code?
问题描述
我必须测量不同 L 值所花费的时间,因此我想优化我的代码.我必须做的是用直径为 d 的周期点 (x,y,z) 填充一个立方体 (LxLxL).到目前为止,这是我所拥有的:
I have to measure the time it takes with varying L values so I want to optimize my code. What I had to do is fill a cubic box (LxLxL) with periodic points (x,y,z) of diameter d that are identical. So far this is what i have:
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 文件):
I then have to output the file (the .xyz file) that is in this format:
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
有什么想法或建议吗?提前致谢!
Any ideas or suggestions? Thanks in advance!
推荐答案
有几件事可以做:首先,将数据格式化与数据生成分开,其次,使用 更简洁的迭代方法.在第一个近似中,将是这样的:
Several things can be done: first, separate data formatting from data generation, second, use a cleaner iteration approach. In the first approximation that would be something like this:
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()
这篇关于重新编写此代码的有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!