问题:从列表中删除多个元素

是否可以同时从列表中删除多个元素?如果我想删除索引0和2的元素,然后尝试类似del somelist[0],然后尝试del somelist[2],则第二条语句实际上将删除somelist[3]

我想我总是可以先删除编号较高的元素,但我希望有更好的方法。

Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].

I suppose I could always delete the higher numbered elements first but I’m hoping there is a better way.


回答 0

可能不是此问题的最佳解决方案:

indices = 0, 2
somelist = [i for j, i in enumerate(somelist) if j not in indices]

You can use enumerate and remove the values whose index matches the indices you want to remove:

indices = 0, 2
somelist = [i for j, i in enumerate(somelist) if j not in indices]

回答 1

由于某种原因,我不喜欢这里的任何答案。是的,它们可以工作,但是严格来说,大多数不是删除列表中的元素,对吗?(但是要进行复制,然后用编辑后的副本替换原始副本)。

为什么不先删除较高的索引呢?

是否有一个原因?我会做:

for i in sorted(indices, reverse=True):
    del somelist[i]

如果您真的不想向后删除项目,那么我想您应该减少大于上一个删除索引的索引值(因为您使用的是不同的列表,所以不能真正使用相同的索引)或使用列表的副本(不会被“删除”,而是将原件替换为已编辑的副本)。

我是否在这里缺少任何东西,有什么理由不以相反的顺序删除?

For some reason I don’t like any of the answers here. Yes, they work, but strictly speaking most of them aren’t deleting elements in a list, are they? (But making a copy and then replacing the original one with the edited copy).

Why not just delete the higher index first?

Is there a reason for this? I would just do:

for i in sorted(indices, reverse=True):
    del somelist[i]

If you really don’t want to delete items backwards, then I guess you should just deincrement the indices values which are greater than the last deleted index (can’t really use the same index since you’re having a different list) or use a copy of the list (which wouldn’t be ‘deleting’ but replacing the original with an edited copy).

Am I missing something here, any reason to NOT delete in the reverse order?


回答 2

如果要删除多个不相邻的项目,那么您描述的是最好的方法(是的,请确保从最高索引开始)。

如果您的项目相邻,则可以使用切片分配语法:

a[2:10] = []

If you’re deleting multiple non-adjacent items, then what you describe is the best way (and yes, be sure to start from the highest index).

If your items are adjacent, you can use the slice assignment syntax:

a[2:10] = []

回答 3

您可以使用numpy.delete以下方法:

import numpy as np
a = ['a', 'l', 3.14, 42, 'u']
I = [0, 2]
np.delete(a, I).tolist()
# Returns: ['l', '42', 'u']

如果您不介意以最后一个numpy数组结尾,则可以省略.tolist()。您还将看到一些相当大的速度改进,从而使它成为更具可扩展性的解决方案。我尚未对其进行基准测试,但是numpy操作是用C或Fortran编写的已编译代码。

You can use numpy.delete as follows:

import numpy as np
a = ['a', 'l', 3.14, 42, 'u']
I = [0, 2]
np.delete(a, I).tolist()
# Returns: ['l', '42', 'u']

If you don’t mind ending up with a numpy array at the end, you can leave out the .tolist(). You should see some pretty major speed improvements, too, making this a more scalable solution. I haven’t benchmarked it, but numpy operations are compiled code written in either C or Fortran.


回答 4

作为Greg答案的一种专业,您甚至可以使用扩展切片语法。例如。如果要删除项目0和2:

>>> a= [0, 1, 2, 3, 4]
>>> del a[0:3:2]
>>> a
[1, 3, 4]

当然,这并不涉及任何选择,但可以删除两个项目。

As a specialisation of Greg’s answer, you can even use extended slice syntax. eg. If you wanted to delete items 0 and 2:

>>> a= [0, 1, 2, 3, 4]
>>> del a[0:3:2]
>>> a
[1, 3, 4]

This doesn’t cover any arbitrary selection, of course, but it can certainly work for deleting any two items.


回答 5

作为功​​能:

def multi_delete(list_, *args):
    indexes = sorted(list(args), reverse=True)
    for index in indexes:
        del list_[index]
    return list_

n log(n)时间运行,这应该使其成为最快的正确解决方案。

As a function:

def multi_delete(list_, *args):
    indexes = sorted(list(args), reverse=True)
    for index in indexes:
        del list_[index]
    return list_

Runs in n log(n) time, which should make it the fastest correct solution yet.


回答 6

因此,您本质上想一次删除多个元素吗?在这种情况下,下一个要删除的元素的位置将被偏移,但是之前删除了许多元素。

我们的目标是删除所有预计算为索引1、4和7的元音。请注意,to_delete索引重要的是升序排列,否则它将不起作用。

to_delete = [1, 4, 7]
target = list("hello world")
for offset, index in enumerate(to_delete):
  index -= offset
  del target[index]

如果您想以任何顺序删除元素,将更加复杂。IMO,排序to_delete可能比弄清楚何时应该从中减去应该不容易index

So, you essentially want to delete multiple elements in one pass? In that case, the position of the next element to delete will be offset by however many were deleted previously.

Our goal is to delete all the vowels, which are precomputed to be indices 1, 4, and 7. Note that its important the to_delete indices are in ascending order, otherwise it won’t work.

to_delete = [1, 4, 7]
target = list("hello world")
for offset, index in enumerate(to_delete):
  index -= offset
  del target[index]

It’d be a more complicated if you wanted to delete the elements in any order. IMO, sorting to_delete might be easier than figuring out when you should or shouldn’t subtract from index.


回答 7

我是Python的初学者,至少我现在的编程很粗糙,但是我的解决方案是结合使用我在早期教程中学到的基本命令:

some_list = [1,2,3,4,5,6,7,8,10]
rem = [0,5,7]

for i in rem:
    some_list[i] = '!' # mark for deletion

for i in range(0, some_list.count('!')):
    some_list.remove('!') # remove
print some_list

显然,由于必须选择“删除标记”字符,因此有其局限性。

至于列表大小可扩展的性能,我确定我的解决方案不是最佳的。但是,它很简单,我希望能吸引其他初学者,并且可以在some_list格式众所周知的简单情况下使用,例如始终为数字…

I’m a total beginner in Python, and my programming at the moment is crude and dirty to say the least, but my solution was to use a combination of the basic commands I learnt in early tutorials:

some_list = [1,2,3,4,5,6,7,8,10]
rem = [0,5,7]

for i in rem:
    some_list[i] = '!' # mark for deletion

for i in range(0, some_list.count('!')):
    some_list.remove('!') # remove
print some_list

Obviously, because of having to choose a “mark-for-deletion” character, this has its limitations.

As for the performance as the size of the list scales, I’m sure that my solution is sub-optimal. However, it’s straightforward, which I hope appeals to other beginners, and will work in simple cases where some_list is of a well-known format, e.g., always numeric…


回答 8

这是一种替代方法,它不使用enumerate()创建元组(如SilentGhost的原始答案)。

这对我来说似乎更具可读性。(如果我习惯于使用枚举,也许会有所不同。)CAVEAT:我尚未测试两种方法的性能。

# Returns a new list. "lst" is not modified.
def delete_by_indices(lst, indices):
    indices_as_set = set(indices)
    return [ lst[i] for i in xrange(len(lst)) if i not in indices_as_set ]

注意:Python 2.7语法。对于Python 3,xrange=> range

用法:

lst = [ 11*x for x in xrange(10) ]
somelist = delete_by_indices( lst, [0, 4, 5])

清单:

[11, 22, 33, 66, 77, 88, 99]

-奖金-

从列表中删除多个值。也就是说,我们具有要删除的值:

# Returns a new list. "lst" is not modified.
def delete__by_values(lst, values):
    values_as_set = set(values)
    return [ x for x in lst if x not in values_as_set ]

用法:

somelist = delete__by_values( lst, [0, 44, 55] )

清单:

[11, 22, 33, 66, 77, 88, 99]

这是与以前相同的答案,但是这次我们提供了要删除的VALUES [0, 44, 55]

Here is an alternative, that does not use enumerate() to create tuples (as in SilentGhost’s original answer).

This seems more readable to me. (Maybe I’d feel differently if I was in the habit of using enumerate.) CAVEAT: I have not tested performance of the two approaches.

# Returns a new list. "lst" is not modified.
def delete_by_indices(lst, indices):
    indices_as_set = set(indices)
    return [ lst[i] for i in xrange(len(lst)) if i not in indices_as_set ]

NOTE: Python 2.7 syntax. For Python 3, xrange => range.

Usage:

lst = [ 11*x for x in xrange(10) ]
somelist = delete_by_indices( lst, [0, 4, 5])

somelist:

[11, 22, 33, 66, 77, 88, 99]

— BONUS —

Delete multiple values from a list. That is, we have the values we want to delete:

# Returns a new list. "lst" is not modified.
def delete__by_values(lst, values):
    values_as_set = set(values)
    return [ x for x in lst if x not in values_as_set ]

Usage:

somelist = delete__by_values( lst, [0, 44, 55] )

somelist:

[11, 22, 33, 66, 77, 88, 99]

This is the same answer as before, but this time we supplied the VALUES to be deleted [0, 44, 55].


回答 9

使用列表索引值的另一种列表理解方法:

stuff = ['a', 'b', 'c', 'd', 'e', 'f', 'woof']
index = [0, 3, 6]
new = [i for i in stuff if stuff.index(i) not in index]

返回:

['b', 'c', 'e', 'f']

An alternative list comprehension method that uses list index values:

stuff = ['a', 'b', 'c', 'd', 'e', 'f', 'woof']
index = [0, 3, 6]
new = [i for i in stuff if stuff.index(i) not in index]

This returns:

['b', 'c', 'e', 'f']

回答 10

这是另一种删除适当元素的方法。同样,如果您的清单很长,则速度会更快。

>>> a = range(10)
>>> remove = [0,4,5]
>>> from collections import deque
>>> deque((list.pop(a, i) for i in sorted(remove, reverse=True)), maxlen=0)

>>> timeit.timeit('[i for j, i in enumerate(a) if j not in remove]', setup='import random;remove=[random.randrange(100000) for i in range(100)]; a = range(100000)', number=1)
0.1704120635986328

>>> timeit.timeit('deque((list.pop(a, i) for i in sorted(remove, reverse=True)), maxlen=0)', setup='from collections import deque;import random;remove=[random.randrange(100000) for i in range(100)]; a = range(100000)', number=1)
0.004853963851928711

here is another method which removes the elements in place. also if your list is really long, it is faster.

>>> a = range(10)
>>> remove = [0,4,5]
>>> from collections import deque
>>> deque((list.pop(a, i) for i in sorted(remove, reverse=True)), maxlen=0)

>>> timeit.timeit('[i for j, i in enumerate(a) if j not in remove]', setup='import random;remove=[random.randrange(100000) for i in range(100)]; a = range(100000)', number=1)
0.1704120635986328

>>> timeit.timeit('deque((list.pop(a, i) for i in sorted(remove, reverse=True)), maxlen=0)', setup='from collections import deque;import random;remove=[random.randrange(100000) for i in range(100)]; a = range(100000)', number=1)
0.004853963851928711

回答 11

已经提到了这一点,但是以某种方式没有人设法正确地做到这一点。

O(n)解决办法是:

indices = {0, 2}
somelist = [i for j, i in enumerate(somelist) if j not in indices]

这确实接近SilentGhost的版本,但增加了两个花括号。

This has been mentioned, but somehow nobody managed to actually get it right.

On O(n) solution would be:

indices = {0, 2}
somelist = [i for j, i in enumerate(somelist) if j not in indices]

This is really close to SilentGhost’s version, but adds two braces.


回答 12

l = ['a','b','a','c','a','d']
to_remove = [1, 3]
[l[i] for i in range(0, len(l)) if i not in to_remove])

它基本上与票数最高的答案相同,只是编写方式不同。注意,使用l.index()不是一个好主意,因为它不能处理列表中的重复元素。

l = ['a','b','a','c','a','d']
to_remove = [1, 3]
[l[i] for i in range(0, len(l)) if i not in to_remove])

It’s basically the same as the top voted answer, just a different way of writing it. Note that using l.index() is not a good idea, because it can’t handle duplicated elements in a list.


回答 13

Remove方法将导致列表元素发生大量移位。我认为最好复制:

...
new_list = []
for el in obj.my_list:
   if condition_is_true(el):
      new_list.append(el)
del obj.my_list
obj.my_list = new_list
...

Remove method will causes a lot of shift of list elements. I think is better to make a copy:

...
new_list = []
for el in obj.my_list:
   if condition_is_true(el):
      new_list.append(el)
del obj.my_list
obj.my_list = new_list
...

回答 14

从技术上讲,答案是否定的,不可能在同一时间删除两个对象。但是,可以在一行漂亮的python中删除两个对象。

del (foo['bar'],foo['baz'])

将删除后foo['bar']foo['baz']

technically, the answer is NO it is not possible to delete two objects AT THE SAME TIME. However, it IS possible to delete two objects in one line of beautiful python.

del (foo['bar'],foo['baz'])

will recusrively delete foo['bar'], then foo['baz']


回答 15

我们可以通过在索引列表降序排序后使用for循环遍历索引来实现此目的

mylist=[66.25, 333, 1, 4, 6, 7, 8, 56, 8769, 65]
indexes = 4,6
indexes = sorted(indexes, reverse=True)
for i in index:
    mylist.pop(i)
print mylist

we can do this by use of a for loop iterating over the indexes after sorting the index list in descending order

mylist=[66.25, 333, 1, 4, 6, 7, 8, 56, 8769, 65]
indexes = 4,6
indexes = sorted(indexes, reverse=True)
for i in index:
    mylist.pop(i)
print mylist

回答 16

对于listA的索引0和2:

for x in (2,0): listA.pop(x)

对于一些要从listA中删除的随机索引:

indices=(5,3,2,7,0) 
for x in sorted(indices)[::-1]: listA.pop(x)

For the indices 0 and 2 from listA:

for x in (2,0): listA.pop(x)

For some random indices to remove from listA:

indices=(5,3,2,7,0) 
for x in sorted(indices)[::-1]: listA.pop(x)

回答 17

我想找到一种比较不同解决方案的方法,这些解决方案可以轻松旋转旋钮。

首先,我生成了数据:

import random

N = 16 * 1024
x = range(N)
random.shuffle(x)
y = random.sample(range(N), N / 10)

然后我定义了我的功能:

def list_set(value_list, index_list):
    index_list = set(index_list)
    result = [value for index, value in enumerate(value_list) if index not in index_list]
    return result

def list_del(value_list, index_list):
    for index in sorted(index_list, reverse=True):
        del(value_list[index])

def list_pop(value_list, index_list):
    for index in sorted(index_list, reverse=True):
        value_list.pop(index)

然后我用来timeit比较解决方案:

import timeit
from collections import OrderedDict

M = 1000
setup = 'from __main__ import x, y, list_set, list_del, list_pop'
statement_dict = OrderedDict([
    ('overhead',  'a = x[:]'),
    ('set', 'a = x[:]; list_set(a, y)'),
    ('del', 'a = x[:]; list_del(a, y)'),
    ('pop', 'a = x[:]; list_pop(a, y)'),
])

overhead = None
result_dict = OrderedDict()
for name, statement in statement_dict.iteritems():
    result = timeit.timeit(statement, number=M, setup=setup)
    if overhead is None:
        overhead = result
    else:
        result = result - overhead
        result_dict[name] = result

for name, result in result_dict.iteritems():
    print "%s = %7.3f" % (name, result)

输出量

set =   1.711
del =   3.450
pop =   3.618

因此,索引为a的生成器set就是赢家。然后del快一点pop

I wanted to a way to compare the different solutions that made it easy to turn the knobs.

First I generated my data:

import random

N = 16 * 1024
x = range(N)
random.shuffle(x)
y = random.sample(range(N), N / 10)

Then I defined my functions:

def list_set(value_list, index_list):
    index_list = set(index_list)
    result = [value for index, value in enumerate(value_list) if index not in index_list]
    return result

def list_del(value_list, index_list):
    for index in sorted(index_list, reverse=True):
        del(value_list[index])

def list_pop(value_list, index_list):
    for index in sorted(index_list, reverse=True):
        value_list.pop(index)

Then I used timeit to compare the solutions:

import timeit
from collections import OrderedDict

M = 1000
setup = 'from __main__ import x, y, list_set, list_del, list_pop'
statement_dict = OrderedDict([
    ('overhead',  'a = x[:]'),
    ('set', 'a = x[:]; list_set(a, y)'),
    ('del', 'a = x[:]; list_del(a, y)'),
    ('pop', 'a = x[:]; list_pop(a, y)'),
])

overhead = None
result_dict = OrderedDict()
for name, statement in statement_dict.iteritems():
    result = timeit.timeit(statement, number=M, setup=setup)
    if overhead is None:
        overhead = result
    else:
        result = result - overhead
        result_dict[name] = result

for name, result in result_dict.iteritems():
    print "%s = %7.3f" % (name, result)

Output

set =   1.711
del =   3.450
pop =   3.618

So the generator with the indices in a set was the winner. And del is slightly faster then pop.


回答 18

您可以使用以下逻辑:

my_list = ['word','yes','no','nice']

c=[b for i,b in enumerate(my_list) if not i in (0,2,3)]

print c

You can use this logic:

my_list = ['word','yes','no','nice']

c=[b for i,b in enumerate(my_list) if not i in (0,2,3)]

print c

回答 19

从最高索引中删除的想法的另一种实现。

for i in range(len(yourlist)-1, -1, -1):
    del yourlist(i)

Another implementation of the idea of removing from the highest index.

for i in range(len(yourlist)-1, -1, -1):
    del yourlist(i)

回答 20

实际上,我可以想到两种方法:

  1. 像这样对列表进行切片(这将删除第1,第3和第8个元素)

    somelist = somelist [1:2] + somelist [3:7] + somelist [8:]

  2. 做到这一点,但一次:

    somelist.pop(2)somelist.pop(0)

I can actually think of two ways to do it:

  1. slice the list like (this deletes the 1st,3rd and 8th elements)

    somelist = somelist[1:2]+somelist[3:7]+somelist[8:]

  2. do that in place, but one at a time:

    somelist.pop(2) somelist.pop(0)


回答 21

您可以对字典而不是列表进行这种操作。在列表中,元素是按顺序排列的。在字典中,它们仅取决于索引。

简单的代码只是为了解释这样做

>>> lst = ['a','b','c']
>>> dct = {0: 'a', 1: 'b', 2:'c'}
>>> lst[0]
'a'
>>> dct[0]
'a'
>>> del lst[0]
>>> del dct[0]
>>> lst[0]
'b'
>>> dct[0]
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    dct[0]
KeyError: 0
>>> dct[1]
'b'
>>> lst[1]
'c'

一种“转换”字典中的列表的方法是:

>>> dct = {}
>>> for i in xrange(0,len(lst)): dct[i] = lst[i]

逆是:

lst = [dct[i] for i in sorted(dct.keys())] 

无论如何,我认为最好从您所说的更高的索引中删除。

You can do that way on a dict, not on a list. In a list elements are in sequence. In a dict they depend only on the index.

Simple code just to explain it by doing:

>>> lst = ['a','b','c']
>>> dct = {0: 'a', 1: 'b', 2:'c'}
>>> lst[0]
'a'
>>> dct[0]
'a'
>>> del lst[0]
>>> del dct[0]
>>> lst[0]
'b'
>>> dct[0]
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    dct[0]
KeyError: 0
>>> dct[1]
'b'
>>> lst[1]
'c'

A way to “convert” a list in a dict is:

>>> dct = {}
>>> for i in xrange(0,len(lst)): dct[i] = lst[i]

The inverse is:

lst = [dct[i] for i in sorted(dct.keys())] 

Anyway I think it’s better to start deleting from the higher index as you said.


回答 22

概括来自@sth的评论。在实现abc.MutableSequence的任何类中list,尤其是通过__delitem__magic方法,都可以删除项目。此方法的工作方式类似于__getitem__,意味着它可以接受整数或切片。这是一个例子:

class MyList(list):
    def __delitem__(self, item):
        if isinstance(item, slice):
            for i in range(*item.indices(len(self))):
                self[i] = 'null'
        else:
            self[item] = 'null'


l = MyList(range(10))
print(l)
del l[5:8]
print(l)

这将输出

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 'null', 'null', 'null', 8, 9]

To generalize the comment from @sth. Item deletion in any class, that implements abc.MutableSequence, and in list in particular, is done via __delitem__ magic method. This method works similar to __getitem__, meaning it can accept either an integer or a slice. Here is an example:

class MyList(list):
    def __delitem__(self, item):
        if isinstance(item, slice):
            for i in range(*item.indices(len(self))):
                self[i] = 'null'
        else:
            self[item] = 'null'


l = MyList(range(10))
print(l)
del l[5:8]
print(l)

This will output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 'null', 'null', 'null', 8, 9]

回答 23

仅出于这个原因导入它可能会过大,但是如果您碰巧正在使用它pandas,则解决方案非常简单明了:

import pandas as pd
stuff = pd.Series(['a','b','a','c','a','d'])
less_stuff = stuff[stuff != 'a']  # define any condition here
# results ['b','c','d']

Importing it only for this reason might be overkill, but if you happen to be using pandas anyway, then the solution is simple and straightforward:

import pandas as pd
stuff = pd.Series(['a','b','a','c','a','d'])
less_stuff = stuff[stuff != 'a']  # define any condition here
# results ['b','c','d']

回答 24

some_list.remove(some_list[max(i, j)])

避免了排序成本,并且不必显式复制列表。

some_list.remove(some_list[max(i, j)])

Avoids sorting cost and having to explicitly copy list.


回答 25

其中之一怎么样(我是Python的新手,但看起来还不错):

ocean_basin = ['a', 'Atlantic', 'Pacific', 'Indian', 'a', 'a', 'a']
for i in range(1, (ocean_basin.count('a') + 1)):
    ocean_basin.remove('a')
print(ocean_basin)

[“大西洋”,“太平洋”,“印度”]

ob = ['a', 'b', 4, 5,'Atlantic', 'Pacific', 'Indian', 'a', 'a', 4, 'a']
remove = ('a', 'b', 4, 5)
ob = [i for i in ob if i not in (remove)]
print(ob)

[“大西洋”,“太平洋”,“印度”]

How about one of these (I’m very new to Python, but they seem ok):

ocean_basin = ['a', 'Atlantic', 'Pacific', 'Indian', 'a', 'a', 'a']
for i in range(1, (ocean_basin.count('a') + 1)):
    ocean_basin.remove('a')
print(ocean_basin)

[‘Atlantic’, ‘Pacific’, ‘Indian’]

ob = ['a', 'b', 4, 5,'Atlantic', 'Pacific', 'Indian', 'a', 'a', 4, 'a']
remove = ('a', 'b', 4, 5)
ob = [i for i in ob if i not in (remove)]
print(ob)

[‘Atlantic’, ‘Pacific’, ‘Indian’]


回答 26

到目前为止提供的答案都不进行删除到位的O(N)在列表的长度为指标,删除任意数量的,所以这里是我的版本:

def multi_delete(the_list, indices):
    assert type(indices) in {set, frozenset}, "indices must be a set or frozenset"
    offset = 0
    for i in range(len(the_list)):
        if i in indices:
            offset += 1
        elif offset:
            the_list[i - offset] = the_list[i]
    if offset:
        del the_list[-offset:]

# Example:
a = [0, 1, 2, 3, 4, 5, 6, 7]
multi_delete(a, {1, 2, 4, 6, 7})
print(a)  # prints [0, 3, 5]

None of the answers offered so far performs the deletion in place in O(n) on the length of the list for an arbitrary number of indices to delete, so here’s my version:

def multi_delete(the_list, indices):
    assert type(indices) in {set, frozenset}, "indices must be a set or frozenset"
    offset = 0
    for i in range(len(the_list)):
        if i in indices:
            offset += 1
        elif offset:
            the_list[i - offset] = the_list[i]
    if offset:
        del the_list[-offset:]

# Example:
a = [0, 1, 2, 3, 4, 5, 6, 7]
multi_delete(a, {1, 2, 4, 6, 7})
print(a)  # prints [0, 3, 5]

回答 27

您也可以使用remove。

delete_from_somelist = []
for i in [int(0), int(2)]:
     delete_from_somelist.append(somelist[i])
for j in delete_from_somelist:
     newlist = somelist.remove(j)

You can use remove, too.

delete_from_somelist = []
for i in [int(0), int(2)]:
     delete_from_somelist.append(somelist[i])
for j in delete_from_somelist:
     newlist = somelist.remove(j)

回答 28

我将所有内容放到一个list_diff函数中,该函数仅将两个列表作为输入并返回它们的差,同时保留第一个列表的原始顺序。

def list_diff(list_a, list_b, verbose=False):

    # returns a difference of list_a and list_b,
    # preserving the original order, unlike set-based solutions

    # get indices of elements to be excluded from list_a
    excl_ind = [i for i, x in enumerate(list_a) if x in list_b]
    if verbose:
        print(excl_ind)

    # filter out the excluded indices, producing a new list 
    new_list = [i for i in list_a if list_a.index(i) not in excl_ind]
    if verbose:
        print(new_list)

    return(new_list)

用法示例:

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'woof']
# index = [0, 3, 6]

# define excluded names list
excl_names_list = ['woof', 'c']

list_diff(my_list, excl_names_list)
>> ['a', 'b', 'd', 'e', 'f']

I put it all together into a list_diff function that simply takes two lists as inputs and returns their difference, while preserving the original order of the first list.

def list_diff(list_a, list_b, verbose=False):

    # returns a difference of list_a and list_b,
    # preserving the original order, unlike set-based solutions

    # get indices of elements to be excluded from list_a
    excl_ind = [i for i, x in enumerate(list_a) if x in list_b]
    if verbose:
        print(excl_ind)

    # filter out the excluded indices, producing a new list 
    new_list = [i for i in list_a if list_a.index(i) not in excl_ind]
    if verbose:
        print(new_list)

    return(new_list)

Sample usage:

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'woof']
# index = [0, 3, 6]

# define excluded names list
excl_names_list = ['woof', 'c']

list_diff(my_list, excl_names_list)
>> ['a', 'b', 'd', 'e', 'f']

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。