简体   繁体   English

在列表中查找第一最大值的索引,将其编译为python中的值

[英]Find index of first max in list compraring to a value in python

I have a sorted list 我有一个排序列表

my_list = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384]

I have a value lets say 445. I want to find the index of first max in list. 我有一个值,可以说445。我想在列表中找到第一个最大值的索引。 For above case, it should return index value 9 (512). 对于上述情况,它应返回索引值9(512)。

The easiest way is to use binary search to find the required index, because the input list is sorted. 最简单的方法是使用二进制搜索来查找所需的索引,因为输入列表已排序。 This algorithm is already implemented in the bisect module: 该算法已在bisect模块中实现:

import bisect

my_list = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384]
print(bisect.bisect_right(my_list, 445))
print(bisect.bisect_right(my_list, 512))

Prints: 印刷品:

9
10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM