简体   繁体   English

如何从python列表中删除特定元素?

[英]How to remove a specific element from a python list?

I want to remove an A element using a B array of IDs, given the specific scalar ID 'C' 我想在给定特定标量ID“C”的情况下使用B数组ID删除A元素

In matlab I can do this: 在matlab中我可以这样做:

A(B == C) = []

This is an example of my code: 这是我的代码示例:

 boxes = [[1,2,20,20],[4,8,20,20],[8,10,40,40]]
 boxIDs = [1,2,3]


IDx = 2

I want to delete the second box completely out of the list. 我想完全删除列表中的第二个框。

How can I do this in python? 我怎么能在python中这样做? I have numpy. 我有笨蛋。

without import numpy you can pop out the element. 没有import numpy你可以pop元素。 try: 尝试:

boxes = [[1,2,20,20],[4,8,20,20],[8,10,40,40]]
IDx = 1
pop_element = boxes.pop(IDx)

the list boxes now is [[1, 2, 20, 20], [8, 10, 40, 40]] and pop_element is [4, 8, 20, 20] 现在列表boxes[[1, 2, 20, 20], [8, 10, 40, 40]] pop_element [[1, 2, 20, 20], [8, 10, 40, 40]] pop_element [[1, 2, 20, 20], [8, 10, 40, 40]]pop_element[4, 8, 20, 20] pop_element [4, 8, 20, 20]

PS: in python indexes start from 0 instead of 1 . PS:在python索引中从0开始而不是1

You could use numpy indexing for that. 你可以使用numpy索引。 You could find more information in the docs . 您可以在文档中找到更多信息。 For your case: 对于你的情况:

import numpy as np
boxes = np.array([[1,2,20,20],[4,8,20,20],[8,10,40,40]])
boxIDs = np.array([1,2,3])

IDx = 2

In [98]: boxes[boxIDs != IDx, :]
Out[98]:
array([[ 1,  2, 20, 20],
       [ 8, 10, 40, 40]])

In plain-old-Python, I think you want to do this: 在普通的Python中,我认为你想这样做:

try:
    helpindex = boxIDs.index(IDx)
    del boxes[index], boxIDs[index]
except ValueError:
    # Already deleted
    pass

Note that if you are relying on boxIDs to be "parallel" with boxes , you have to make sure you keep them parallel by deleting from both. 请注意,如果您依赖boxIDsboxes “并行”,则必须确保通过从两者中删除来保持它们的平行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM