我有一个二维数组。每行有3个值(不一定是唯一的),例如:
[ [3, 4, 1],
[8, 1, 3],
[5, 6, 5] ]
有一个过程可以生成3个数字的列表。我检查此列表是否已经存在于我的数组中(相同编号和相同序列),如果存在,请忽略它,如果不存在,则将其添加到数组中。此过程运行多次。
我检查存在的方式是通过循环:
c = 0
for s in range(len(l)):
if np.array_equal(l[s], new):
c = 1
break
if c == 0:
l = np.append(l, new).reshape(-1, 3)
其中l是我的列表,new是该过程生成的列表。
我的问题是,有没有一种方法可以不使用循环进行检查。如果列表太大(如100k +行),则检查过程将花费太多时间。请指导。
您可以broadcasting
一次性完成所有行的矢量化检查,如下所示-
if ~(np.all(l == new,1)).any():
l = np.append(l, new).reshape(-1, 3)
样品运行-
In [288]: l
Out[288]:
array([[4, 4, 0],
[1, 4, 1],
[0, 4, 4],
[4, 0, 4],
[2, 4, 2]])
In [289]: new
Out[289]: [7, 0, 4]
In [290]: if ~(np.all(l == new,1)).any():
...: l = np.append(l, new).reshape(-1, 3)
...:
In [291]: l
Out[291]:
array([[4, 4, 0],
[1, 4, 1],
[0, 4, 4],
[4, 0, 4],
[2, 4, 2],
[7, 0, 4]])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句