我有以下Python 2.7代码,可从设备查询运动限制:
pan_low_limit = int(self.send_query("PN", 2))
pan_high_limit = int(self.send_query("PX", 2))
tilt_low_limit = int(self.send_query("TN", 2))
tilt_high_limit = int(self.send_query("TX", 2))
我想我可以这样写:
limits = [(pan_low_limit, "PN"), (pan_high_limit, "PX"), (tilt_low_limit, "TN"), (tilt_high_limit, "TX")]
for v, c in limits:
v = int(self.send_query(c, 2))
print("Result from {}: {}".format(c, v))
print(limits)
print("tilt_low_limit: {}".format(tilt_low_limit))
打印语句用于查找发生的情况。运行此命令时,得到以下输出(这四个代码在此代码段之前已用值1初始化):
Result from PN: -27067
Result from PX: 27067
Result from TN: -27999
Result from TX: 9333
[(1, 'PN'), (1, 'PX'), (1, 'TN'), (1,'TX')]
tilt_low_limit: 1
PN: 1
我真的不了解发生了什么。似乎"v = int(self.send_query(c, 2))"
中的v值是我所期望的,但是在下一行,这些变量又具有旧值了?
答案 0 :(得分:1)
这就是您想要的:
for i, (v, c) in enumerate(limits):
limits[i] = int(self.send_query(c, 2))
v =
不会更改limits
中的值,它只会更改引用/变量v
的值。
答案 1 :(得分:0)
在Python中,符号名(如代码中的pan_low_limit
)是对值(如“ -27067”)的引用。
将一个名称分配给另一个名称时(如代码中的limits
和v
),新名称将成为对该值的附加引用。对于您而言,在赋值之前的第一次迭代中,名称:pan_low_limit
,limits[0][0]
和v
都指向相同的值:
但是,当您为新值分配(或 bind )名称时,只有该名称将引用新值。就您而言,分配后,您将拥有:
要获得所需的结果,您应该 change 变量,而不是重新分配它,以便所有引用都引用相同的新值。但是,整数是不可变的,因此您无法更改它。 解决方案是使用可变的东西,例如 list 。
如果您有一个可变变量,则可以将原始值更改为具有您期望的结果。您可以在以下两个片段中看到这种差异:
使用整数:
pan_low_limit = 1
pan_high_limit = 1
tilt_low_limit = 1
tilt_high_limit = 1
limits = [(pan_low_limit, "PN"), (pan_high_limit, "PX"), (tilt_low_limit, "TN"), (tilt_high_limit, "TX")]
for v, c in limits:
v = 2
print("Result from {}: {}".format(c, v))
print(limits)
print("tilt_low_limit: {}".format(tilt_low_limit))
结果:
Result from PN: 2
Result from PX: 2
Result from TN: 2
Result from TX: 2
[(1, 'PN'), (1, 'PX'), (1, 'TN'), (1, 'TX')]
tilt_low_limit: 1
使用列表,我们可以修改值,而不用重新分配它:
pan_low_limit = [1]
pan_high_limit = [1]
tilt_low_limit = [1]
tilt_high_limit = [1]
limits = [(pan_low_limit, "PN"), (pan_high_limit, "PX"), (tilt_low_limit, "TN"), (tilt_high_limit, "TX")]
for v, c in limits:
v[0] = 2
print("Result from {}: {}".format(c, v))
print(limits)
print("tilt_low_limit: {}".format(tilt_low_limit))
结果:
Result from PN: [2]
Result from PX: [2]
Result from TN: [2]
Result from TX: [2]
[([2], 'PN'), ([2], 'PX'), ([2], 'TN'), ([2], 'TX')]
tilt_low_limit: [2]
参考:link
感谢@bruno desthuilliers指出了先前答案中的缺陷。