gpt4 book ai didi

Python/Numpy : How do I renumber an existing array with repeating instances?

转载 作者:行者123 更新时间:2023-12-01 07:26:06 25 4
gpt4 key购买 nike

我有以下数组:(3,2,3,4,7,2,4,7)*我需要将其重新编号为:(1,0,1,2,3,0,2,3)

即:最低值应变为 0,第二低值应变为 1,依此类推

我能找到的类似帖子每个数字只有一个实例,并且相关答案不适用于此处,因为重复的数字应该具有相同的重新编号值。

谢谢

  • 实际数组有数千个数字。

最佳答案

这可能不是最有效的解决方案,因为我怀疑其中有一些俏皮话,但我希望它是明智且直接的:

from collections import defaultdict

ary = [3,2,3,4,7,2,4,7]

#you don't need a defaultdict, but I like to use them just in case, instead of a dictionary, as a general practice
rank = defaultdict(int)

for x in ary: #first, we get all the values of the array and put them in the dict
rank[x] = 0

count = 0

for x in sorted(rank): #now we go from lowest to highest in the array, adding 1 to the dict-value
rank[x] = count
count += 1

ary = [rank[x] for x in ary]

print(ary)

关于Python/Numpy : How do I renumber an existing array with repeating instances?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57443521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com