新手 Python 用户在这里,真的难倒这个。我有一个 3x3 数组,它以 xyz 格式存储坐标,其中行是原子数,列对应于 x、y 和 z。对于不在 z 方向上的每个元素,我希望为其添加一些标量 dr。最终,我想生成一个包含 6 个几何图形的字典,在每个实例中,元素 x0、y0、x0、y1、x1、y0 等中的一个都添加了标量。现在我只是尝试编写一个函数来执行此操作并在每次迭代时打印出几何图形。
这是我编写的函数的更简单版本。在这里,我循环遍历行和列,使用参考几何 (geom) 的参数以及行和列的两个索引调用函数。对于每个 X 和 Y 坐标,该函数将 dr 添加到几何并返回其值。
import numpy as np
dr = 0.1
principle_axes = 'Z'
def displace(coords, row, col):
if principle_axes == 'Z':
if col != 2:
new_coords = coords
new_coords[row, col] = new_coords[row, col] + dr
return new_coords
geom = np.array([[0, 0, 0.1435], [0, 0, 2.992], [0, 0, -2.8993]])
[nR, nC] = np.shape(geom)
if nR == 3 and nC == 3:
import pdb; pdb.set_trace() # XXX BREAKPOINT
for i in range(nR):
for j in range(nC):
print(geom)
displaced_geom = displace(geom, i, j)
print(displaced_geom)
对于循环的每次迭代,该函数都会获取最后一次迭代的返回几何值,即使调用的参数 (geom) 在循环期间没有重新分配。这给了我这个geom的示例输出......
[[ 0. 0. 0.1435]
[ 0. 0. 2.992 ]
[ 0. 0. -2.8993]]
[[ 0.1 0. 0.1435]
[ 0. 0. 2.992 ]
[ 0. 0. -2.8993]]
[[ 0.1 0.1 0.1435]
[ 0. 0. 2.992 ]
[ 0. 0. -2.8993]]
打印displaced_geom 的输出是相同的。我希望得到的输出是:
[[ 0. 0. 0.1435]
[ 0. 0. 2.992 ]
[ 0. 0. -2.8993]]
[[ 0.1 0. 0.1435]
[ 0. 0. 2.992 ]
[ 0. 0. -2.8993]]
[[ 0. 0.1 0.1435]
[ 0. 0. 2.992 ]
[ 0. 0. -2.8993]]
[[ 0. 0. 0.1435]
[ 0.1 0. 2.992 ]
[ 0. 0. -2.8993]]
然后我可以弄清楚如何将每次迭代的结果存储在字典中,并在以后的代码中使用它来做一些事情。仅供参考,我在 Ubuntu 16.04.6 LTS 上运行 Python3.5.2。如果有人可以帮助我了解我哪里出了问题并指出我正确的方向,那就太好了。