问题:如何通过索引从列表中删除元素
如何在Python中按索引从列表中删除元素?
我找到了list.remove
方法,但是说我要删除最后一个元素,该怎么做?似乎默认的remove搜索列表,但是我不希望执行任何搜索。
How do I remove an element from a list by index in Python?
I found the list.remove
method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don’t want any search to be performed.
回答 0
使用del
并指定要删除的元素的索引:
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[-1]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]
还支持切片:
>>> del a[2:4]
>>> a
[0, 1, 4, 5, 6, 7, 8, 9]
这是教程中的部分。
Use del
and specify the index of the element you want to delete:
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[-1]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Also supports slices:
>>> del a[2:4]
>>> a
[0, 1, 4, 5, 6, 7, 8, 9]
Here is the section from the tutorial.
回答 1
您可能想要pop
:
a = ['a', 'b', 'c', 'd']
a.pop(1)
# now a is ['a', 'c', 'd']
默认情况下,pop
不带任何参数将删除最后一项:
a = ['a', 'b', 'c', 'd']
a.pop()
# now a is ['a', 'b', 'c']
You probably want pop
:
a = ['a', 'b', 'c', 'd']
a.pop(1)
# now a is ['a', 'c', 'd']
By default, pop
without any arguments removes the last item:
a = ['a', 'b', 'c', 'd']
a.pop()
# now a is ['a', 'b', 'c']
回答 2
像其他提到的一样,pop和del是删除给定索引项的有效方法。只是为了完成(因为可以通过Python中的许多方法来完成同一件事):
使用切片(这并不能代替从原始列表中删除项目):
(这也是使用Python列表时效率最低的方法,但是在使用不支持pop但却定义了a的用户定义对象时,这可能会很有用(但无效,我重申__getitem__
)。
>>> a = [1, 2, 3, 4, 5, 6]
>>> index = 3 # Only positive index
>>> a = a[:index] + a[index+1 :]
# a is now [1, 2, 3, 5, 6]
注意:请注意,此方法不会像pop
和那样修改列表del
。相反,它制作了两个列表副本(一个从开始到索引,但没有索引(a[:index]
),一个在索引后,直到最后一个元素(a[index+1:]
)),并通过添加两个副本来创建新的列表对象。然后将其重新分配给列表变量(a
)。因此,旧列表对象被取消引用并因此被垃圾回收(前提是原始列表对象未被a以外的任何变量引用)。
这使该方法非常低效,并且还可能产生不良的副作用(尤其是当其他变量指向未修改的原始列表对象时)。
感谢@MarkDickinson指出这一点…
该堆栈溢出答案说明了切片的概念。
另请注意,这仅适用于正指数。
与对象一起使用时,__getitem__
必须已定义该__add__
方法,更重要的是,必须已定义该方法以从两个操作数返回包含项的对象。
本质上,这适用于类定义如下的任何对象:
class foo(object):
def __init__(self, items):
self.items = items
def __getitem__(self, index):
return foo(self.items[index])
def __add__(self, right):
return foo( self.items + right.items )
这与list
定义__getitem__
和__add__
方法一起使用。
三种方式的效率比较:
假设以下是预定义的:
a = range(10)
index = 3
该del object[index]
方法:
迄今为止最有效的方法。所有定义__del__
方法的对象都可以使用。
拆卸如下:
码:
def del_method():
global a
global index
del a[index]
拆卸:
10 0 LOAD_GLOBAL 0 (a)
3 LOAD_GLOBAL 1 (index)
6 DELETE_SUBSCR # This is the line that deletes the item
7 LOAD_CONST 0 (None)
10 RETURN_VALUE
None
pop
方法:
它比del方法效率低,在需要获取已删除项目时使用。
码:
def pop_method():
global a
global index
a.pop(index)
拆卸:
17 0 LOAD_GLOBAL 0 (a)
3 LOAD_ATTR 1 (pop)
6 LOAD_GLOBAL 2 (index)
9 CALL_FUNCTION 1
12 POP_TOP
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
slice和add方法。
效率最低。
码:
def slice_method():
global a
global index
a = a[:index] + a[index+1:]
拆卸:
24 0 LOAD_GLOBAL 0 (a)
3 LOAD_GLOBAL 1 (index)
6 SLICE+2
7 LOAD_GLOBAL 0 (a)
10 LOAD_GLOBAL 1 (index)
13 LOAD_CONST 1 (1)
16 BINARY_ADD
17 SLICE+1
18 BINARY_ADD
19 STORE_GLOBAL 0 (a)
22 LOAD_CONST 0 (None)
25 RETURN_VALUE
None
注意:在所有三个反汇编中,忽略最后两行,基本上是return None
。同样,前两行正在加载全局值a
和index
。
Like others mentioned pop and del are the efficient ways to remove an item of given index. Yet just for the sake of completion (since the same thing can be done via many ways in Python):
Using slices (this does not do in place removal of item from original list):
(Also this will be the least efficient method when working with Python list, but this could be useful (but not efficient, I reiterate) when working with user defined objects that do not support pop, yet do define a __getitem__
):
>>> a = [1, 2, 3, 4, 5, 6]
>>> index = 3 # Only positive index
>>> a = a[:index] + a[index+1 :]
# a is now [1, 2, 3, 5, 6]
Note: Please note that this method does not modify the list in place like pop
and del
. It instead makes two copies of lists (one from the start until the index but without it (a[:index]
) and one after the index till the last element (a[index+1:]
)) and creates a new list object by adding both. This is then reassigned to the list variable (a
). The old list object is hence dereferenced and hence garbage collected (provided the original list object is not referenced by any variable other than a).
This makes this method very inefficient and it can also produce undesirable side effects (especially when other variables point to the original list object which remains un-modified).
Thanks to @MarkDickinson for pointing this out …
This Stack Overflow answer explains the concept of slicing.
Also note that this works only with positive indices.
While using with objects, the __getitem__
method must have been defined and more importantly the __add__
method must have been defined to return an object containing items from both the operands.
In essence, this works with any object whose class definition is like:
class foo(object):
def __init__(self, items):
self.items = items
def __getitem__(self, index):
return foo(self.items[index])
def __add__(self, right):
return foo( self.items + right.items )
This works with list
which defines __getitem__
and __add__
methods.
Comparison of the three ways in terms of efficiency:
Assume the following is predefined:
a = range(10)
index = 3
The del object[index]
method:
By far the most efficient method. It works will all objects that define a __del__
method.
The disassembly is as follows:
Code:
def del_method():
global a
global index
del a[index]
Disassembly:
10 0 LOAD_GLOBAL 0 (a)
3 LOAD_GLOBAL 1 (index)
6 DELETE_SUBSCR # This is the line that deletes the item
7 LOAD_CONST 0 (None)
10 RETURN_VALUE
None
pop
method:
It is less efficient than the del method and is used when you need to get the deleted item.
Code:
def pop_method():
global a
global index
a.pop(index)
Disassembly:
17 0 LOAD_GLOBAL 0 (a)
3 LOAD_ATTR 1 (pop)
6 LOAD_GLOBAL 2 (index)
9 CALL_FUNCTION 1
12 POP_TOP
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
The slice and add method.
The least efficient.
Code:
def slice_method():
global a
global index
a = a[:index] + a[index+1:]
Disassembly:
24 0 LOAD_GLOBAL 0 (a)
3 LOAD_GLOBAL 1 (index)
6 SLICE+2
7 LOAD_GLOBAL 0 (a)
10 LOAD_GLOBAL 1 (index)
13 LOAD_CONST 1 (1)
16 BINARY_ADD
17 SLICE+1
18 BINARY_ADD
19 STORE_GLOBAL 0 (a)
22 LOAD_CONST 0 (None)
25 RETURN_VALUE
None
Note: In all three disassembles ignore the last two lines which basically are return None
. Also the first two lines are loading the global values a
and index
.
回答 3
从列表中删除并保留项目也很有用。del
实际在哪里丢弃物品。
>>> x = [1, 2, 3, 4]
>>> p = x.pop(1)
>>> p
2
is also useful to remove and keep an item from a list. Where del
actually trashes the item.
>>> x = [1, 2, 3, 4]
>>> p = x.pop(1)
>>> p
2
回答 4
如果要删除列表中的特定位置元素,例如2th,3th和7th。你不能使用
del my_list[2]
del my_list[3]
del my_list[7]
由于删除第二个元素后,实际上删除的第三个元素是原始列表中的第四个元素。您可以过滤原始列表中的2th,3th和7th元素并获得一个新列表,如下所示:
new list = [j for i, j in enumerate(my_list) if i not in [2, 3, 7]]
If you want to remove the specific position element in a list, like the 2th, 3th and 7th. you can’t use
del my_list[2]
del my_list[3]
del my_list[7]
Since after you delete the second element, the third element you delete actually is the fourth element in the original list. You can filter the 2th, 3th and 7th element in the original list and get a new list, like below:
new list = [j for i, j in enumerate(my_list) if i not in [2, 3, 7]]
回答 5
这取决于您要做什么。
如果要返回删除的元素,请使用pop()
:
>>> l = [1, 2, 3, 4, 5]
>>> l.pop(2)
3
>>> l
[1, 2, 4, 5]
但是,如果您只想删除一个元素,请使用del
:
>>> l = [1, 2, 3, 4, 5]
>>> del l[2]
>>> l
[1, 2, 4, 5]
另外,del
允许您使用切片(例如del[2:]
)。
This depends on what you want to do.
If you want to return the element you removed, use pop()
:
>>> l = [1, 2, 3, 4, 5]
>>> l.pop(2)
3
>>> l
[1, 2, 4, 5]
However, if you just want to delete an element, use del
:
>>> l = [1, 2, 3, 4, 5]
>>> del l[2]
>>> l
[1, 2, 4, 5]
Additionally, del
allows you to use slices (e.g. del[2:]
).
回答 6
通常,我使用以下方法:
>>> myList = [10,20,30,40,50]
>>> rmovIndxNo = 3
>>> del myList[rmovIndxNo]
>>> myList
[10, 20, 30, 50]
Generally, I am using the following method:
>>> myList = [10,20,30,40,50]
>>> rmovIndxNo = 3
>>> del myList[rmovIndxNo]
>>> myList
[10, 20, 30, 50]
回答 7
通过索引从列表中删除元素的另一种方法。
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# remove the element at index 3
a[3:4] = []
# a is now [0, 1, 2, 4, 5, 6, 7, 8, 9]
# remove the elements from index 3 to index 6
a[3:7] = []
# a is now [0, 1, 2, 7, 8, 9]
a [x:y]指向索引中的元素 x
到y-1
。当我们将列表的该部分声明为空列表([]
)时,这些元素将被删除。
Yet another way to remove an element(s) from a list by index.
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# remove the element at index 3
a[3:4] = []
# a is now [0, 1, 2, 4, 5, 6, 7, 8, 9]
# remove the elements from index 3 to index 6
a[3:7] = []
# a is now [0, 1, 2, 7, 8, 9]
a[x:y] points to the elements from index x
to y-1
. When we declare that portion of the list as an empty list ([]
), those elements are removed.
回答 8
您可以只搜索要删除的项目。真的很简单。例:
letters = ["a", "b", "c", "d", "e"]
letters.remove(letters[1])
print(*letters) # Used with a * to make it unpack you don't have to (Python 3.x or newer)
输出:acde
You could just search for the item you want to delete. It is really simple. Example:
letters = ["a", "b", "c", "d", "e"]
letters.remove(letters[1])
print(*letters) # Used with a * to make it unpack you don't have to (Python 3.x or newer)
Output: a c d e
回答 9
使用以下代码从列表中删除元素:
list = [1, 2, 3, 4]
list.remove(1)
print(list)
output = [2, 3, 4]
如果要从列表中删除索引元素数据,请使用:
list = [1, 2, 3, 4]
list.remove(list[2])
print(list)
output : [1, 2, 4]
Use the following code to remove element from the list:
list = [1, 2, 3, 4]
list.remove(1)
print(list)
output = [2, 3, 4]
If you want to remove index element data from the list use:
list = [1, 2, 3, 4]
list.remove(list[2])
print(list)
output : [1, 2, 4]
回答 10
如前所述,最佳实践是del(); 或pop()如果您需要知道该值。
另一种解决方案是仅重新堆叠所需的那些元素:
a = ['a', 'b', 'c', 'd']
def remove_element(list_,index_):
clipboard = []
for i in range(len(list_)):
if i is not index_:
clipboard.append(list_[i])
return clipboard
print(remove_element(a,2))
>> ['a', 'b', 'd']
eta:嗯…不适用于负索引值,会思考和更新
我想
if index_<0:index_=len(list_)+index_
会修补它…但是突然之间,这个想法似乎很脆弱。有趣的思想实验。似乎应该有一个“正确”的方法来执行append()/列表理解。
思考
As previously mentioned, best practice is del(); or pop() if you need to know the value.
An alternate solution is to re-stack only those elements you want:
a = ['a', 'b', 'c', 'd']
def remove_element(list_,index_):
clipboard = []
for i in range(len(list_)):
if i is not index_:
clipboard.append(list_[i])
return clipboard
print(remove_element(a,2))
>> ['a', 'b', 'd']
eta: hmm… will not work on negative index values, will ponder and update
I suppose
if index_<0:index_=len(list_)+index_
would patch it… but suddenly this idea seems very brittle. Interesting thought experiment though. Seems there should be a ‘proper’ way to do this with append() / list comprehension.
pondering
回答 11
听起来好像您不是在使用列表列表,所以我将简短说明。您要使用pop,因为它将删除元素而不是列表元素,因此应使用del。要调用python中的最后一个元素,它是“ -1”
>>> test = ['item1', 'item2']
>>> test.pop(-1)
'item2'
>>> test
['item1']
It doesn’t sound like you’re working with a list of lists, so I’ll keep this short. You want to use pop since it will remove elements not elements that are lists, you should use del for that. To call the last element in python it’s “-1”
>>> test = ['item1', 'item2']
>>> test.pop(-1)
'item2'
>>> test
['item1']
回答 12
l-值列表;我们必须从inds2rem列表中删除索引。
l = range(20)
inds2rem = [2,5,1,7]
map(lambda x: l.pop(x), sorted(inds2rem, key = lambda x:-x))
>>> l
[0, 3, 4, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
l – list of values; we have to remove indexes from inds2rem list.
l = range(20)
inds2rem = [2,5,1,7]
map(lambda x: l.pop(x), sorted(inds2rem, key = lambda x:-x))
>>> l
[0, 3, 4, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
回答 13
使用“ del”功能:
del listName[-N]
例如,如果要删除最后3个项目,则代码应为:
del listName[-3:]
例如,如果要删除最后8个项目,则代码应为:
del listName[-8:]
Use the “del” function:
del listName[-N]
For example, if you want to remove the last 3 items, your code should be:
del listName[-3:]
For example, if you want to remove the last 8 items, your code should be:
del listName[-8:]
回答 14
已经提到了如何从列表中删除单个元素以及不同方法具有哪些优点。但是请注意,删除多个元素可能会导致错误:
>>> l = [0,1,2,3,4,5,6,7,8,9]
>>> indices=[3,7]
>>> for i in indices:
... del l[i]
...
>>> l
[0, 1, 2, 4, 5, 6, 7, 9]
原始列表的元素3和8(不是3和7)已被删除(因为列表在循环中被缩短了),这可能不是本意。如果要安全删除多个索引,则应首先删除索引最高的元素,例如:
>>> l = [0,1,2,3,4,5,6,7,8,9]
>>> indices=[3,7]
>>> for i in sorted(indices, reverse=True):
... del l[i]
...
>>> l
[0, 1, 2, 4, 5, 6, 8, 9]
It has already been mentioned how to remove a single element from a list and which advantages the different methods have. Note, however, that removing multiple elements has some potential for errors:
>>> l = [0,1,2,3,4,5,6,7,8,9]
>>> indices=[3,7]
>>> for i in indices:
... del l[i]
...
>>> l
[0, 1, 2, 4, 5, 6, 7, 9]
Elements 3 and 8 (not 3 and 7) of the original list have been removed (as the list was shortened during the loop), which might not have been the intention. If you want to safely remove multiple indices you should instead delete the elements with highest index first, e.g. like this:
>>> l = [0,1,2,3,4,5,6,7,8,9]
>>> indices=[3,7]
>>> for i in sorted(indices, reverse=True):
... del l[i]
...
>>> l
[0, 1, 2, 4, 5, 6, 8, 9]
回答 15
或者,如果应删除多个索引:
print([v for i,v in enumerate(your_list) if i not in list_of_unwanted_indexes])
然后当然也可以这样做:
print([v for i,v in enumerate(your_list) if i != unwanted_index])
Or if multiple indexes should be removed:
print([v for i,v in enumerate(your_list) if i not in list_of_unwanted_indexes])
Of course then could also do:
print([v for i,v in enumerate(your_list) if i != unwanted_index])
回答 16
您可以使用del或pop来基于索引从列表中删除元素。Pop将打印从列表中删除的成员,而列表删除该成员而不打印它。
>>> a=[1,2,3,4,5]
>>> del a[1]
>>> a
[1, 3, 4, 5]
>>> a.pop(1)
3
>>> a
[1, 4, 5]
>>>
You can use either del or pop to remove element from list based on index. Pop will print member it is removing from list, while list delete that member without printing it.
>>> a=[1,2,3,4,5]
>>> del a[1]
>>> a
[1, 3, 4, 5]
>>> a.pop(1)
3
>>> a
[1, 4, 5]
>>>
回答 17
可以使用del或pop,但我更喜欢del,因为您可以指定索引和切片,从而使用户可以更好地控制数据。
例如,从所示的列表开始,可以使用删除其最后一个元素del
作为切片,然后可以使用从结果中删除最后一个元素pop
。
>>> l = [1,2,3,4,5]
>>> del l[-1:]
>>> l
[1, 2, 3, 4]
>>> l.pop(-1)
4
>>> l
[1, 2, 3]
One can either use del or pop, but I prefer del, since you can specify index and slices, giving the user more control over the data.
For example, starting with the list shown, one can remove its last element with del
as a slice, and then one can remove the last element from the result using pop
.
>>> l = [1,2,3,4,5]
>>> del l[-1:]
>>> l
[1, 2, 3, 4]
>>> l.pop(-1)
4
>>> l
[1, 2, 3]
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。