说我在这里有这个列表:
list = [a, b, c, d, e, f, g]
Run Code Online (Sandbox Code Playgroud)
我如何删除说索引2, 3, 4,5同时?
pop不接受多个值.我怎么做呢?
Ned*_*der 174
您需要在循环中执行此操作,没有内置操作一次删除多个索引.
您的示例实际上是一个连续的索引序列,因此您可以这样做:
del my_list[2:6]
Run Code Online (Sandbox Code Playgroud)
从2开始删除切片,在6之前结束.
从您的问题中不清楚一般是否需要删除任意索引集合,或者它是否始终是连续的序列.
如果您有任意索引集合,那么:
indexes = [2, 3, 5]
for index in sorted(indexes, reverse=True):
del my_list[index]
Run Code Online (Sandbox Code Playgroud)
请注意,您需要以相反的顺序删除它们,以免丢弃后续索引.
Igo*_*bin 30
remove_indices = [1,2,3]
somelist = [i for j, i in enumerate(somelist) if j not in remove_indices]
Run Code Online (Sandbox Code Playgroud)
例:
In [9]: remove_indices = [1,2,3]
In [10]: somelist = range(10)
In [11]: somelist = [i for j, i in enumerate(somelist) if j not in remove_indices]
In [12]: somelist
Out[12]: [0, 4, 5, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)
And*_*ris 16
对于不同的方式没有太多关于性能的提示,所以我在所有3种通常不同的方法中执行了从50000中删除5000个项目的测试,对我来说numpy是赢家(如果你有适合numpy的元素):
这是我定时的代码(如果直接在numpy数组上运行,可以删除第三个函数从/到列表的转换):
import time
import numpy as np
import random
def del_list_indexes(l, id_to_del):
somelist = [i for j, i in enumerate(l) if j not in id_to_del]
return somelist
def del_list_inplace(l, id_to_del):
for i in sorted(id_to_del, reverse=True):
del(l[i])
def del_list_numpy(l, id_to_del):
arr = np.array(l, dtype='int32')
return list(np.delete(arr, id_to_del))
l = range(50000)
random.shuffle(l)
remove_id = random.sample(range(len(l)), 5000) # 10% ==> 5000
# ...
Run Code Online (Sandbox Code Playgroud)
Ant*_*ony 12
如果它们是连续的,你就可以做到
x[2:6] = []
Run Code Online (Sandbox Code Playgroud)
如果要删除不连续的索引,则有点棘手.
x = [v for i,v in enumerate(x) if i not in frozenset((2,3,4,5))]
Run Code Online (Sandbox Code Playgroud)
如果你可以使用numpy,那么你可以删除多个索引:
>>> import numpy as np
>>> a = np.arange(10)
>>> np.delete(a,(1,3,5))
array([0, 2, 4, 6, 7, 8, 9])
Run Code Online (Sandbox Code Playgroud)
如果您使用,np.r_您可以将切片与单个索引组合:
>>> np.delete(a,(np.r_[0:5,7,9]))
array([5, 6, 8])
Run Code Online (Sandbox Code Playgroud)
但是,删除不是in place,所以你必须分配给它.
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
lst = lst[0:2] + lst[6:]
Run Code Online (Sandbox Code Playgroud)
这是一个单步操作。它不使用循环,因此执行速度很快。它使用列表切片。
| 归档时间: |
|
| 查看次数: |
108503 次 |
| 最近记录: |