繁体   English   中英

Python - 在 For 循环内调用函数 - 更改输入参数而不覆盖它

[英]Python - Calling a Function Inside a For Loop - Changing Input Argument Without Overwriting It

这里的新手 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。 如果有人能帮助我了解我哪里出错了,并指出我正确的方向,那就太好了。

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

new_coords = coords分配一个指针,而不是一个副本。

您可以改为执行new_coords = coords.copy()以免覆盖。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM