首页 > 解决方案 > 如何将浮点数组转换为唯一整数数组?

问题描述

我有一个浮点数组,我想将它转换为一个整数数组,这样整数数组包含与 np.arange(array_of_floats) 相同的元素。我希望对整数数组进行排序以反映浮点数组中元素的相对大小。

例如,如果浮点数数组中索引为 5 的元素是第三小,则整数数组中索引为 5 的元素应该是 2。

如果浮点数数组中索引为 3 的元素是最小的,则整数数组中索引为 3 的元素应该为 0。

举一些例子:

floats = [1.2, 3.4, 2.1, 0.4]
# I want to generate the following array:
integers = [1, 3, 2, 0]

另一个例子:

floats = [5.4, 2.3, 6.2, 1.2, 7.4, 3.2]
integers = [3, 1, 4, 0, 5, 2]

标签: python-3.x

解决方案


您可以对浮点数列表进行排序,并将排序列表中的浮点数映射到它们在原始列表中的索引:

floats = [1.2, 3.4, 2.1, 0.4]

sorted_floats = sorted(floats)

integers = list(map(sorted_floats.index, floats))

print(integers)

输出:

[1, 3, 2, 0]

推荐阅读