检查给定浮点数在列表中的哪个浮点数之间 [英] Check between which floats in a list a given float falls

查看:65
本文介绍了检查给定浮点数在列表中的哪个浮点数之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的列表:

I have a list that looks like this:

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

我需要遍历如下所示的浮点列表:

I need to iterate through a list of floats that looks like this:

# 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]

检查列表b中每个元素在列表a中的哪些元素之间,并返回a中的元素的索引(在右侧).例如,对于上方的列表b,结果将如下所示:

check between which elements in list a each element in list b falls, and return the index of the element in a (to the right). For example, for the list b above the results would look like:

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

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

(notice the index 7 which points to an extra element in a associated to > max(a))

我可以通过一个如下所示的精致的for/if循环来做到这一点,但是我想知道是否有一种我可能不知道的函数可能更简单的方法(欢迎使用numpy/scipy函数)

I could do this with a rather elaborated for/if loop as shown below, but I was wondering if there might be an easier way with some function I might not be aware of (numpy/scipy functions are welcomed)

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解决方案是 bisect 模块,该模块具有用于二进制搜索的几种功能:

The ordinary Python solution is the bisect module, which has several functions for binary search:

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

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

The NumPy solution is numpy.searchsorted, which does much the same:

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

这篇关于检查给定浮点数在列表中的哪个浮点数之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆