python:use a 函数来删除一个列表元素,我和resu搞混了

2024-10-02 22:35:54 发布

您现在位置:Python中文网/ 问答频道 /正文

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]也起作用)


Tags: 函数元素hello列表responsedefpopst
2条回答

popf变异传递给它的st列表testf没有:它只是用另一个列表覆盖名称,该列表是没有第一个元素的副本

在第一个函数中,您将在该语句中为st赋值,因此它是一个全新的变量,而不是作为参数传递的变量:

st = st[1:]

可以在赋值前后使用id进行检查:

In [13]: def testf(st):
   ....:     print('before: ', id(st))
   ....:     st = st[1:]
   ....:     print('after: ', id(st))
   ....:

In [14]: a = ["response", ["wis", "hello"], ["deng", "shen"]]

In [15]: id(a)
Out[15]: 85287112L

In [16]: testf(a)
('before: ', 85287112L)
('after: ', 85289480L)

但是在第二个函数中没有赋值,因此id保持不变。这意味着您修改了传入参数的列表:

In [17]: def popf(st):
   ....:     print('before: ', id(st))
   ....:     st.pop(0)
   ....:     print('after: ', id(st))
   ....:

In [18]: popf(a)
('before: ', 85287112L)
('after: ', 85287112L)

相关问题 更多 >