首页 文章

如何在Python中通过索引从列表中删除元素?

提问于
浏览
1127

如何在Python中通过索引从列表中删除元素?

我找到了 list.remove 方法,但是说我要删除最后一个元素,我该怎么做?似乎默认删除搜索列表,但我不希望执行任何搜索 .

18 回答

  • 4

    像其他人一样,pop和del是删除给定索引项的有效方法 . 然而,仅仅是为了完成(因为在Python中可以通过多种方式完成同样的事情):

    Using slices (this does not do in place removal of item from original list):

    (这也是使用Python列表时效率最低的方法,但是在处理不支持pop的用户定义对象时,这可能很有用(但是效率不高,我重申),但确实定义了 __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: 请注意,此方法不会像 popdel 那样修改列表 . 它改为生成两个列表副本(一个从开始到索引但没有它( a[:index] ),一个在索引之后直到最后一个元素( a[index+1:] ))并通过添加两个来创建一个新的列表对象 . 然后将其重新分配给列表变量( a ) . 因此,旧的列表对象被解除引用并因此被垃圾收集(假设原始列表对象不被除了a之外的任何变量引用) .

    这使得该方法效率非常低并且还可能产生不期望的副作用(特别是当其他变量指向原始列表对象时仍未修改) .

    感谢@MarkDickinson指出这一点......

    This Stack Overflow答案解释了切片的概念 .

    另请注意,这仅适用于正指数 .

    在使用对象时,必须定义 __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 )
    

    这适用于定义 __getitem____add__ 方法的 list .

    Comparison of the three ways in terms of efficiency:

    假设以下是预定义的:

    a = range(10)
    index = 3
    

    The del object[index] method:

    到目前为止最有效的方法 . 它适用于定义 __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 method:

    它的效率低于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
    

    The slice and add method.

    效率最低 .

    码:

    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 . 前两行也加载了全局值 aindex .

  • 44

    如前所述,最佳实践是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()/ list comprehension .

    琢磨

  • 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']
    
  • 13

    您可以使用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]
    >>>
    
  • 4

    您可以简单地使用Python的remove函数 . 像这样:

    v = [1, 2, 3, 4, 5, 6]
    v.remove(v[4]) # I'm removing the number with index 4 of my array
    print(v) # If you want verify the process
    
    # It gave me this:
    #[1,2,3,4,6]
    
  • 4

    这取决于你想做什么 .

    如果要返回删除的元素,请使用 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:] ) .

  • 106

    另一种通过索引从列表中删除元素的方法 .

    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]指向从索引 xy-1 的元素 . 当我们将列表的该部分声明为空列表( [] )时,将删除这些元素 .

  • 7

    使用 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]
    

    Here是教程中的部分 .

  • -1

    使用 "del" 函数:

    del listName[-N]
    

    例如,如果要删除最后3项,则代码应为:

    del listName[-3:]
    

    例如,如果要删除最后8个项目,则代码应为:

    del listName[-8:]
    
  • 9

    pop对于从列表中删除和保留项目也很有用 . del 实际上会破坏该项目 .

    >>> x = [1, 2, 3, 4]
    
    >>> p = x.pop(1)
    >>> p
        2
    
  • 1312

    一般来说,我使用以下方法:

    >>> myList = [10,20,30,40,50]
    >>> rmovIndxNo = 3
    >>> del myList[rmovIndxNo]
    >>> myList
    [10, 20, 30, 50]
    
  • 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]
    
  • 0

    如果要删除列表中的特定位置元素,例如2号,3号和7号 . 你不能用

    del my_list[2]
    del my_list[3]
    del my_list[7]
    

    由于删除第二个元素后,实际删除的第三个元素是原始列表中的第四个元素 . 你可以过滤原始列表中的第2,第3和第7个元素并获得一个新列表,如下所示:

    new list = [j for i, j in enumerate(my_list) if i not in [2, 3, 7]]
    
  • 526

    您只需搜索要删除的项目即可 . 这很简单 . 例:

    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)
    

    输出:a c d e

  • 4

    使用以下代码从列表中删除元素:

    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]
    
  • 0

    这听起来并不像你正在使用列表列表,所以我会保持这个简短 . 你想使用pop,因为它将删除元素而不是列表元素,你应该使用del . 要调用python中的最后一个元素,它是“-1”

    >>> test = ['item1', 'item2']
    >>> test.pop(-1)
    'item2'
    >>> test
    ['item1']
    
  • 5

    或者,如果应删除多个索引:

    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])
    
  • 1

    可以使用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]
    

相关问题