我有一个正整数的类似列表的Python对象,我想要获取该列表中重复值的位置。例如,如果输入为
[0,1,1]
,则函数应该返回[1,2]
,因为元素1在输入数组的位置1和2处出现了两次。同样地:
[0,13,13]
应该返回 [[1, 2]]
[0,1,2,1,3,4,2,2]
应该返回 [[1, 3], [2, 6, 7]]
,因为1
在输入数组的位置[1, 3]处出现了两次,2
在位置[2, 6, 7]处出现了3次。
[1, 2, 3]
应该返回一个空列表[]
我的代码如下:def get_locations(labels):
out = []
label_set = set(labels)
for label in list(label_set):
temp = [i for i, j in enumerate(labels) if j == label]
if len(temp) > 1:
out.append(np.array(temp))
return np.array(out)
当输入数组较小时,它可以正常工作,但随着规模的增长,速度变得过慢。例如,下面的代码在我的电脑上,当n = 1000
时从0.14秒
飙升到12秒
,
from timeit import default_timer as timer
start = timer()
n = 10000
a = np.arange(n)
b = np.append(a, a[-1]) # append the last element to the end
out = get_locations(b)
end = timer()
print(out)
print(end - start) # Time in seconds
请问有什么方法可以加速这个过程吗?非常感谢任何建议。