2016-09-26 73 views
0

我正在Python(3.5)的pop()函數上做書練習。說明是使用pop()從列表中刪除元素。從下面的列表中,我想刪除n1,n4,n5,n6,n7,n8,n9。下面的代碼工作,但非常實用),我不明白爲什麼特定的索引只能工作到[5]。沒有使用循環(我還沒有),從列表中彈出特定元素的正確方法是什麼?從列表中刪除(彈出)特定元素

nameList = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9'] 
print('I can only invite two people to dinner...') 

print('Sorry, but ', nameList.pop(0).title(), ' will not be invited to 
     dinner') 
print('Sorry, but ', nameList.pop(3).title(), ' will not be invited to 
     dinner') 
print('Sorry, but ', nameList.pop(4).title(), ' will not be invited to 
     dinner') 
print('Sorry, but ', nameList.pop(5).title(), ' will not be invited to 
     dinner') 
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to 
     dinner') 
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to 
     dinner') 
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to 
     dinner') 

回答

2

輸出是:

I can only invite two people to dinner... 
('Sorry, but ', 'N1', ' will not be invited todinner') 
('Sorry, but ', 'N5', ' will not be invited to dinner') 
('Sorry, but ', 'N7', ' will not be invited to dinner') 
('Sorry, but ', 'N9', ' will not be invited to dinner') 
('Sorry, but ', 'N8', ' will not be invited to dinner') 
('Sorry, but ', 'N6', ' will not be invited to dinner') 
('Sorry, but ', 'N4', ' will not be invited to dinner') 

讓我們來看看它:

起初你的列表中有9個元素。您刪除先用pop(0)所以現在你有即8個元素的列表:

['n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9'] 

不是你從這個「新」名單,這是n5(記住索引從0開始)

刪除這是第3 elelemnt

依此類推...

每次刪除後,列表將會變短,所以即使在第一次刪除之後,第八個刪除位置的元素也會被刪除(這種情況發生在您的案例中pop(5)之後) 。

沒有從列表中刪除元素的「常規」方式,但請注意列表是可變變量。

1

那麼,每次使用'pop'時,nameList的長度都會動態變化。 所以彈出4個元素(n1,n4,n5,n6)後,nameList中只剩下5個元素。 您不能再使用pop(5),因爲索引當時超出範圍。

0

具體的索引作用如同所有索引的魅力直到列表大小。你遇到的問題是,當你從列表中刪除一個元素時,縮小它,每次彈出時,大小減少1。

說你有3個要素,l = ["a","b","c"] 你彈出第一個l.pop(0),將返回"a"的列表,但它也將修改清單,因此現在l等於["b","c"]。 如果您彈出最後一個項目l.pop(2)l.pop(-1)(因爲Python允許您從最後一個元素中統計元素,所以-1總是列表的最後一個元素),您將得到"c"和列表l本來會變成["a","b"]。 請注意,在這兩種情況下,列表都會縮小,並且只剩下兩個元素,所以您將無法立即彈出元素編號2,因爲沒有這種情況。

如果要讀取元素而不是將其從列表中刪除,請使用myList[elementIndex]語法。例如,在您的示例中,nameList[6]將返回"n7",但它根本不會修改該列表。

0

發生這種情況是因爲每次從列表中彈出某個元素時,列表長度都會發生變化。所以,如果你想使用pop具體而言,去除指定元素的簡單而取巧的辦法將是以下幾點:

>>> nameList = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9'] 
>>> 
>>> nameList.pop(nameList.index('n1')) 
'n1' 
>>> nameList.pop(nameList.index('n4')) 
'n4' 
>>> nameList.pop(nameList.index('n5')) 
'n5' 
>>> nameList.pop(nameList.index('n6')) 
'n6' 
>>> nameList.pop(nameList.index('n7')) 
'n7' 
>>> nameList.pop(nameList.index('n8')) 
'n8' 
>>> nameList.pop(nameList.index('n9')) 
'n9' 
>>> nameList 
['n2', 'n3'] 

因此,大家可以看到我們每次彈出一個元素時,我們指定其index所以我們不」不存在列表長度變化的問題 - 因爲使用index,我們將獲得元素的新索引!正如你所看到的結果將是:['n2', 'n3']正如所料!