以下是输出:
[['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]也可以)。
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 aBelow is the output:
[['wis', 'hello'], ['deng', 'shen']] ['response', ['wis', 'hello'], ['deng', 'shen']] [['wis', 'hello'], ['deng', 'shen']] [['wis', 'hello'], ['deng', 'shen']]I want to use a function to delete a list element, but I'm confused why the function testf() can't delete the element after the function but the popf() function can do. what's the difference? if not in the function, st=st[1:] = st.pop(0) (del st[0] also works).
最满意答案
在第一个函数中,您在此语句中为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)In first function you are assigning a new value to st in this statement so it is a completely new variable and not the one passed as the argument:
st = st[1:]You can check it using id before and after assignment:
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)But in the second function there is no assignment hence the id remains same. It means you modified the list passed in the arguments:
In [17]: def popf(st): ....: print('before: ', id(st)) ....: st.pop(0) ....: print('after: ', id(st)) ....: In [18]: popf(a) ('before: ', 85287112L) ('after: ', 85287112L)更多推荐
发布评论