从Python中的列表中删除索引列表

Tha*_*y07 5 python

我有一个带有点(质心)的列表,其中一些必须被删除.

我怎么能没有循环呢?我已经尝试了这里给出的答案,但显示了以下错误:

list indices must be integers, not list
Run Code Online (Sandbox Code Playgroud)

我的列表看起来像这样:

centroids = [[320, 240], [400, 200], [450, 600]]
index = [0,2]
Run Code Online (Sandbox Code Playgroud)

我想删除中的元素index.最终结果将是:

centroids = [[400, 200]]
Run Code Online (Sandbox Code Playgroud)

Kas*_*mvd 9

您可以enumerate在列表理解中使用:

>>> centroids = [[320, 240], [400, 200], [450, 600]]
>>> index = [0,2]
>>> [element for i,element in enumerate(centroids) if i not in index]
[[400, 200]]
Run Code Online (Sandbox Code Playgroud)

请注意,最后您必须遍历列表以查找特殊索引,并且没有办法在没有循环的情况下执行此操作.但你可以使用在C语言中执行的列表理解,并且比python循环更快(比快2倍)!

另外,为了获得更高的性能,您可以将索引放在set具有O(1)的容器中以检查成员资格.


小智 5

这是另一种非常有趣的方式。

 map(centroids.__delitem__, sorted(index, reverse=True))
Run Code Online (Sandbox Code Playgroud)

它实际上会就地删除项目。