python-3.x - 如何将浮点数组转换为唯一整数数组?
问题描述
我有一个浮点数组,我想将它转换为一个整数数组,这样整数数组包含与 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]
解决方案
您可以对浮点数列表进行排序,并将排序列表中的浮点数映射到它们在原始列表中的索引:
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]
推荐阅读
- swift - 如何以编程方式查找视图的纵横比?
- ionic3 - 如何使用城市名称搜索离子存储并获取城市 ID
- javascript - 在 Windows/Linux 机器的 Canvas 中渲染时提高线条清晰度(设备像素比 < 2)?
- python - Tkinter 用 Selenium python 冻结
- php - 无法上传数据库中的文件
- python-3.x - 在 python 中更新 AWS Lambda 函数的环境变量
- json - 需要帮助修复 homebridge 插件的 JSON
- batch-file - 为什么我的 Jenkins Doxygen make.bat 不工作?
- python - 什么是使 find_monthly_savings 函数返回金额除以 Python 中一年(十二个月)中的月份的正确方法
- php - 如何在 laravel 中配置多认证的 web 路由和 api 路由?