[英]How to remove a specific element from a python list?
我想在給定特定標量ID“C”的情況下使用B數組ID刪除A元素
在matlab中我可以這樣做:
A(B == C) = []
這是我的代碼示例:
boxes = [[1,2,20,20],[4,8,20,20],[8,10,40,40]]
boxIDs = [1,2,3]
IDx = 2
我想完全刪除列表中的第二個框。
我怎么能在python中這樣做? 我有笨蛋。
沒有import numpy
你可以pop
元素。 嘗試:
boxes = [[1,2,20,20],[4,8,20,20],[8,10,40,40]]
IDx = 1
pop_element = boxes.pop(IDx)
現在列表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:在python索引中從0
開始而不是1
。
你可以使用numpy索引。 您可以在文檔中找到更多信息。 對於你的情況:
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]])
在普通的Python中,我認為你想這樣做:
try:
helpindex = boxIDs.index(IDx)
del boxes[index], boxIDs[index]
except ValueError:
# Already deleted
pass
請注意,如果您依賴boxIDs
與boxes
“並行”,則必須確保通過從兩者中刪除來保持它們的平行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.