python - 如何从列表中的最大数字到最小数字获取索引?
问题描述
我正在用 Python 编写一个小项目:
我想从以下列表中从最高到最小的数字获取索引(在列表中):
list = [20, 30, 24, 26, 22, 10]
结果应该是:
index_list = [1, 3, 2, 4, 0, 5]
任何人都知道我该怎么做?提前致谢。
解决方案
我对python编程很陌生,但这似乎可行:
list = [20, 30, 24, 26, 22, 10]
list_sorted = list.copy()
list_sorted.sort()
list_index = []
for x in list_sorted:
list_index.insert(0,list.index(x))
print(list_index)
输出:
[1, 3, 2, 4, 0, 5]
因为上面会产生不正确的值,所以存在重复,请参见下一个:
list = [20, 10, 24, 26, 22, 10]
list_tmp = list.copy()
list_sorted = list.copy()
list_sorted.sort()
list_index = []
for x in list_sorted:
list_index.insert(0,list_tmp.index(x))
list_tmp[list_tmp.index(x)] = -1
print(list)
print(list_index)
输出:
[20, 10, 24, 26, 22, 10]
[3, 2, 4, 0, 5, 1]
输出是否[3, 2, 4, 0, 5, 1]
或[3, 2, 4, 0, 1, 5]
因为这些索引引用相同的值无关紧要。
推荐阅读
- sql - 从表中获取列数据类型和一些条件
- java - Lucene 搜索匹配短语中的任何单词
- kotlin - 如何在 kotlin gradle DSL 中配置 kotlin 测试输出?
- excel - 按原样将文本从 Excel 复制到 Outlook 邮件
- angular - IntelliJ 找不到从 stylePreprocessorOptions includePaths 导入的 scss
- php - 从 html 格式 PHP 中的 Curl 响应中获取数据
- python - UnboundLocalError:分配前引用的局部变量“batch_index”
- jquery - 如何使用jquery ajax实时更新div内容
- kubernetes - helm 有打印功能吗?
- angular - 角度,ng-zorro:对象作为标签