列表作为函数参数 - 修改丢弃 [英] List as a function argument - modifications discarded
问题描述
我有以下code
def hidePasswords(L, password):
for elem in L:
if elem == password:
elem = "*"*len(password)
return L
print(hidePasswords(["test","test1","test8"],"test"))
它返回 ['测试','TEST1','test8']
而不是 ['****','TEST1' test8']
。当我改变我的功能
It returns ['test', 'test1', 'test8']
instead of ['****', 'test1', 'test8']
. When I change my function to
def hidePasswords(L, password):
temp = []
for elem in L:
if elem == password:
elem = "*"*len(password)
temp.append(elem)
return temp
它工作正常。
为什么Python的以这样的方式表现?我完全理解在第二code会发生什么,但我不明白的第一个行为。
Why does Python behaves in such a way? I perfectly understand what happens in second code, but I don't understand behaviour of the first one.
推荐答案
在此code:
def hidePasswords(L, password):
for elem in L:
if elem == password:
elem = "*"*len(password)
return L
在循环中, ELEM
正在以→
设置为每个值。然后重新分配 ELEM
是不同的东西。因此,它的已的在 L中的值
,则是另一回事。这并不影响值→
,因为 ELEM
不是一个参考。
In the loop, elem
is being set to each value in L
. Then you reassign elem
to be something different. So it was the value in L
, then it is something else. That doesn't affect the value in L
, because elem
isn't a reference.
您可以更简洁地写为:
def hidePasswords(L, password):
return ['*'*len(password) if elem==password else elem for elem in L]
这篇关于列表作为函数参数 - 修改丢弃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!