2016-04-23 33 views
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 a 

下面困惑是輸出:蟒蛇:使用函數刪除列表元素,不然我和結果

[['wis', 'hello'], ['deng', 'shen']] 
['response', ['wis', 'hello'], ['deng', 'shen']] 
[['wis', 'hello'], ['deng', 'shen']] 
[['wis', 'hello'], ['deng', 'shen']] 

我想用一個函數來刪除列表元素,但我m困惑爲什麼功能testf()不能刪除功能後的元素,但功能可以做到。有什麼不同?如果不在該功能中,st=st[1:] = st.pop(0)del st[0]也有效)。

回答

0

在第一個功能,你在這個聲明中分配一個新的價值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) 
0

popf發生變異,它是通過st列表。 testf不會:它只是用另一個沒有第一個元素的副本列表覆蓋名稱。