2016-09-26 67 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']正如所料!