def testf(st):
st=st[1:]
print st
def popf(st):
st.pop(0)
print st
a = ["response", ["wis", "hello"], ["deng", "shen"]]
testf(a)
print a
a = ["response", ["wis", "hello"], ["deng", "shen"]]
popf(a)
print a
以下是输出:
[['wis', 'hello'], ['deng', 'shen']]
['response', ['wis', 'hello'], ['deng', 'shen']]
[['wis', 'hello'], ['deng', 'shen']]
[['wis', 'hello'], ['deng', 'shen']]
我想用一个函数来删除列表元素,但我不明白为什么函数testf()
不能删除函数后面的元素,而函数popf()
可以。有什么区别?如果不在函数中,st=st[1:] = st.pop(0)
(del st[0]
也起作用)
popf
变异传递给它的st
列表testf
没有:它只是用另一个列表覆盖名称,该列表是没有第一个元素的副本在第一个函数中,您将在该语句中为
st
赋值,因此它是一个全新的变量,而不是作为参数传递的变量:可以在赋值前后使用
id
进行检查:但是在第二个函数中没有赋值,因此id保持不变。这意味着您修改了传入参数的列表:
相关问题 更多 >
编程相关推荐