在Python中查找介于0到100之间的值范围内的索引 - python

这是一个分为两部分的问题,我必须通过列表中任意数量的整数的随机范围来选择2个索引。如果它们都在相同范围内,也无法返回

Selection1 = random.randint(0,100)
Selection2 = random.randint(0,100)

为了这个论点,请说:

Selection1 = 10
Selection2 = 17
And the list would be like so [25, 50, 75, 100]

两者都将返回索引0,因为它们介于0-25之间

因此,两者都将落入第一个索引范围,问题是我在尝试将其放入此范围(IE:0-25)时遇到了一些问题,这将返回该第一个索引(返回列表[0])

python中这种逻辑的语法是什么?

我敢肯定,如果它们属于同一范围,我可以弄清楚如何返回不同的索引,可能只是将循环重置为循环,但是如果我能得到一些建议,那将不会有什么坏处。

我将给出我现在正在使用的代码作为准则。大多数情况下,我在苦苦挣扎。

在这里编码

def roulette_selection(decimal_list, chromosome_fitness, population):
    percentages = []
    for i in range(population):
        result = decimal_list[i]/chromosome_fitness
        result = result * 100
        percentages.append(result)

    print(percentages)
    range_in_fitness = []
    current_percent = 0

    for i in range(population):
        current_percent = percentages[i] + current_percent
        range_in_fitness.append(current_percent)
    parent1 = random.randint(0, 100)
    parent2 = random.randint(0, 100)

    for i in range(population):
        if parent1 >= range_in_fitness[i] and parent1<=range_in_fitness[i+1]:


    print(parent1, parent2)
    print(range_in_fitness)

python大神给出的解决方案

如果您对范围列表进行了排序,或者可以对它进行排序并且是连续的(没有空格),则可以使用Python的bisect模块以高效的方式进行操作。例:

>>> l = [25, 50, 75, 100]
>>> import bisect
>>> bisect.bisect(l, 10)
0
>>> bisect.bisect(l, 17)
0
>>> bisect.bisect(l, 55)
2
>>> bisect.bisect(l, 25)
1

Bisect返回输入数字应落入列表以保持排序顺序的位置的索引。请注意,起初这有点令人困惑。在上述55的情况下,它返回2,因为它应插入索引2,因为它介于索引12的当前值之间。如果您准确地在范围边界上给它一个数字,则它会“落在右边”,如bisect(l,25)所示。

链接的文档包括一组配方,可使用bisect在排序列表中进行搜索。