【问题标题】:Check between which floats in a list a given float falls检查给定浮点数落在列表中的哪个浮点数之间
【发布时间】:2014-08-01 13:42:20
【问题描述】:

我有一个如下所示的列表:

# Ordered list.
a = [0.1, 0.3, 0.4, 0.5, 0.6, 0.7, 0.9]

我需要遍历一个看起来像这样的浮点列表:

# Not ordered list.
b = [0.12, 0.53, 0.30, 0.03, 0.77, 0.62, 0.98, 0.01, 0.42, 0.33, 1.3]

检查列表a中的哪些元素在列表b中的每个元素落下,并返回a中元素的索引(向右)。例如,对于上面的列表b,结果如下所示:

indxs = [1, 4, 2, 0, 6, 5, 7, 0, 3, 2, 7]

(注意索引 7 指向 a 中与 > max(a) 关联的一个额外元素)

我可以用一个相当详细的for/if 循环来做到这一点,如下所示,但我想知道是否有更简单的方法来处理一些我可能不知道的函数(numpy/scipy 函数是受欢迎的)

MWE:

indxs = []
for b_el in b:
    # Check if float is to the right of max(a)
    if b_el > max(a):
        indxs.append(len(a))
    else:
        for a_el in a:
            if b_el < a_el:
                indxs.append(a.index(a_el))
                break
            elif b_el == a_el:
                indxs.append(a.index(a_el) + 1)
                break

【问题讨论】:

    标签: python list numpy


    【解决方案1】:

    普通的Python解决方案是bisect模块,对binary search有几个函数:

    >>> [bisect.bisect(a, x) for x in b]
    [1, 4, 2, 0, 6, 5, 7, 0, 3, 2, 7]
    

    NumPy 解决方案是numpy.searchsorted,其作用大致相同:

    >>> numpy.searchsorted(a, b, side='right')
    array([1, 4, 2, 0, 6, 5, 7, 0, 3, 2, 7], dtype=int64)
    

    【讨论】:

      【解决方案2】:

      这是一个表达式:

      where(b<=a.max(),argmax((b[:,None] - a) < 0,axis=1),len(a))
      

      (如果 a 和 b 是数组)

      【讨论】:

        猜你喜欢
        • 2011-07-14
        • 2020-07-17
        • 2012-11-18
        • 1970-01-01
        • 2019-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多