简体   繁体   English

Python,list.remove() 不正确

[英]Python, list.remove() does not work right

Hello I am trying to remove first and last 2 element of my list.您好,我正在尝试删除列表中的第一个和最后两个元素。 My list is: ['12','30','22','06','27','13','23','16','14','20','09','29','23']我的列表是: ['12','30','22','06','27','13','23','16','14','20','09','29','23']

and this is the code I am using:这是我正在使用的代码:

dList.remove(dList[0])
dList.remove(dList[-1])
dList.remove(dList[-1])

It works right too many other list but in this list it returns:它适用于太多其他列表,但在此列表中它返回:

['30', '22', '06', '27', '13', '16', '14', '20', '09', '29']

Instead of;代替;

['30', '22', '06', '27', '13', '23', '16', '14', '20', '09',]

I noticed the last element is '23' and both '23' be removed but I don't know how to fix it.我注意到最后一个元素是“23”,两个“23”都被删除了,但我不知道如何修复它。 It should be work right because I remove first element, and last element, and last element again.它应该可以正常工作,因为我再次删除了第一个元素、最后一个元素和最后一个元素。 I didn't use:我没有使用:

a = dList[0]
dList.remove(a)
a = dList[-1]
dList.remove(a)
a = dList[-1]
dList.remove(a)

The remove() method removes the first matching element (which is passed as an argument) from the list. remove() 方法从列表中删除第一个匹配元素(作为参数传递)。

You have 23 repeated twice.你有23重复了两次。

If you want to remove index you can use del in your example.it would be:如果要删除索引,可以在示例中使用del 。它将是:

del dList[-1]

this should work这应该工作

dList = dList[1:-2]

Why not using pop to pop out the last element of the list?为什么不使用pop弹出列表的最后一个元素?

last_element = dList.pop()
semilast_element = dList.pop()

You can even put the index of the element you want to pop您甚至可以放置要弹出的元素的索引

first_element = dList.pop(0)
second_element = dList.pop(0)

Always refer to the original documentation始终参考原始文档

With:和:

dList = ['12','30','22','06','27','13','23','16','14','20','09','29','23']

...you could construct a new list with a slice (as previously suggested) like this: ...您可以使用切片(如前所述)构造一个新列表,如下所示:

dList = dList[1:-2] dList = dList[1:-2]

...or you can do it in situ using pop() as follows: ...或者您可以使用pop()就地进行操作,如下所示:

dList.pop(0)
dList.pop()
dList.pop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM