我对mapPython中的函数有疑问.
根据我的理解,该函数不会改变它正在运行的列表,而是创建一个新的并返回它.它是否正确 ?
另外,我有以下代码
def reflect(p,dir):
if(dir == 'X'):
func = lambda (a,b) : (a * -1, b)
else:
func = lambda (a,b) : (a, b * -1)
p = map(func,p)
print 'got', p
Run Code Online (Sandbox Code Playgroud)
points 是一个元组数组,如: [(1, 1), (-1, 1), (-1, -1), (1, -1)]
如果我以这种方式调用上述函数:
print points
reflect(points,'X')
print points
Run Code Online (Sandbox Code Playgroud)
列表points不会改变.但是在功能内部,打印功能可以正确打印出我想要的内容.
有人可能指点我在某个方向,我可以学习如何通过值/参考等传递如何在python中工作,以及我如何解决上述问题?或许我在努力模仿Python中的Haskell ......
谢谢
编辑:
说而不是p = map(func,p)我
for i in range(len(p)):
p[i] = func(p[i])
Run Code Online (Sandbox Code Playgroud)
列表的值在函数外部更新,就像通过引用一样工作.呃,希望这很清楚:S
Cat*_*lus 12
你误解了引用如何在Python中工作.这里,所有名称都是引用,没有"值".名称绑定到对象.但是=不修改名称所指向的对象 - 它将名称重新绑定到另一个对象:
x = 42
y = x
# now:
# 'is' is a identity operator — it checks whether two names point to the
# exact same object
print x is y # => True
print x, y # 42 42
y = 69
# now y has been rebound, but that does not change the '42' object, nor rebinds x
print x is y # => False
print x, y # 42 69
Run Code Online (Sandbox Code Playgroud)
要修改对象本身,它需要是可变的 - 即暴露成员改变它或具有可修改的字典.重新绑定时会发生与上述相同的事情p- 它根本不触及points,它只是修改了本地p名称的含义.
如果要模拟类似C++的引用,则需要将对象封装到可变容器中,例如列表.
reflect([points], 'X')
# inside reflect:
p[0] = ...
Run Code Online (Sandbox Code Playgroud)
但是你不应该,至少在这种情况下 - 你应该只返回新对象.
points = reflect(points, 'X')
# inside reflect, instead of p = ...
return map(func, p)
Run Code Online (Sandbox Code Playgroud)
那么,既然我想到了,你也可以这样做
p[:] = map(func, p)
Run Code Online (Sandbox Code Playgroud)
但同样,返回新对象通常会更好.
| 归档时间: |
|
| 查看次数: |
2936 次 |
| 最近记录: |