![](/img/trans.png)
[英]What's the most efficient way to replace some given indices of a NumPy array?
[英]Given an array, what's an efficient way to create an array of arrays where each of these subarrays has indices with equal values from the given array
假設我有一個大小為 n 的數組,其中包含一些浮點值。 我想創建一個包含子數組的新數組,其中每個子數組都將包含原始數組中具有相等值的所有元素的索引。 因此,例如,給定數組 givenArray=[50,20,50,20,40],答案將是 resultArray=[[0,2],[1,3],[4]]。
蠻力方式是對原數組進行迭代,在每次迭代中,對結果數組進行迭代,將值與每個子數組中的第一個值進行比較; 如果等於它,在那里添加它的索引。 如果不等於任何子數組的第一個值,則創建一個新的子數組並將其索引放在那里。 python 中的代碼如下:
resultArray=[]
for i in range(0,len(givenArray)):
flag=0
for j in range(0,len(resultArray)):
if(givenArray[i]==givenArray[resultArray[j][0]]):
resultArray[j].append(i)
flag=1
if(flag==0):
resultArray.append([i])
該解決方案的復雜度為 O(n^2)。 這可以以更好的復雜性完成嗎? 如何? 想法和 python 代碼將不勝感激! 非常感謝!
阿里
您可以使用defaultdict
和enumerate
在線性時間內執行此操作:
from collections import defaultdict
result = defaultdict(list)
for i, n in enumerate(givenArray):
result[n].append(i)
# {50: [0, 2], 20: [1, 3], 40: [4]}
result = [*result.values()]
# [[0, 2], [1, 3], [4]]
但是請注意,您的示例具有int
值而不是float
。 float
作為字典鍵的表現不太好,因為它們可能會出現舍入或精度錯誤,尤其是當它們是某種計算的結果時。
@schwobaseggl 的 dict 答案可能是最好的,但為了完整起見,這里有一個使用groupby的解決方案。
此解決方案按值的遞增順序返回組。
import operator
import itertools
def group_indices(array):
sorted_with_indices = sorted(enumerate(array), key=operator.itemgetter(1))
groups = itertools.groupby(sorted_with_indices, key=operator.itemgetter(1))
return [[i for i,v in g] for k,g in groups]
print(group_indices([50,20,50,20,40]))
# [[1, 3], [4], [0, 2]]
相關文件:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.