在图片中,我的数组如下所示:

我想知道如何用以下逻辑返回数组(Newarr)(这里是伪代码):我需要尽可能快地实现它!请帮助在python中以正确和快速的方式编写它。(也许使用numpy,我知道numpy是快速的)
i=0
for x in arraynumpy
i=i+1
for y in arraynumpy[0:i-1]
if x[0]==y[1] and x[1]==y[0] and x[2]==y[2]
newarr.append(x)
continue; # break the loop for y,if found与图片中的输入相同,返回的数组为:[20,10,'1',30,10,'1']
谢谢
发布于 2022-06-20 12:24:49
你的伪码是二次时间。这里有一个线性时间的解决方案(如果你有大量的输入,它会更好)。它不使用numpy数组,因为我认为这无助于获得更好的性能。
def find_stuff(l):
result = []
index = set()
for x1, x2, x3 in l:
if (x2, x1, x3) in index:
result.append((x1, x2, x3))
index.add((x1, x2, x3))
return result在你的例子中:
>>> a = [(10, 20, 1), (10, 30, 1), (10, 50, 1), (10, 108, 1), (10, 200010, 1), (20, 10, 1), (20, 108, 1), (20, 710, 1), (20, 710, 1), (20, 200020, 1), (30, 10, 1)]
>>> find_stuff(a)
[(20, 10, 1), (30, 10, 1)]
>>> 请注意,如果您确实需要更好的性能,也许您应该考虑使用另一种语言,因为Python非常慢。
https://stackoverflow.com/questions/72686199
复制相似问题