如何查看列表中是否有一个值介于另一个列表的两个值之间

how to see if there is a value in a list that is between two values from another list

我有两个列表

a = [1, 4, 12]
b = [2, 13]

我想知道 list b 中的值是否介于 list a 中的两个值之间 因此,在这种情况下,2 将落在 1 和 4 之间。13 不会落在任何数字之间。

我试过 bisect 功能,但我无法让它工作。我能够将它与单个值和一个列表一起使用,但不能与两个列表一起使用。

您可以保留两个 运行 索引以获取落在值之间的所有元素的列表:

def get_between(arr1, arr2):
    # first sort the arrays
    arr1 = sorted(arr1)
    arr2 = sorted(arr2)
    # keep two indices into them
    i1 = 0
    i2 = 0
    # keep track of the values between two values
    ret = []
    while i1 < len(arr1) - 1 and i2 < len(arr2):
        # we're too small to be between a value
        # so we should increase the second index
        if arr2[i2] < arr1[i1]:
            i2 += 1
        # we're too large to be between a value
        # so we should increase the first index
        elif arr2[i2] > arr1[i1 + 1]:
            i1 += 1
        # we are between a value
        # so we should append to the return array
        # and move on to the next element
        else:
            ret.append(arr2[i2])
            i2 += 1
    return ret

get_between([1, 4, 12], [2, 8, 13]) # [2, 8]

这真的取决于你想要什么 return。我编写了一个代码,它将 return 它找到的第一个模式,但通过一些更改,我相信 return 所有组合并不困难。

def get_between(a, b):
    a, b = sorted(a), sorted(b)
    
    for b_value in b:
        smaller = None
        greater = None
        for a_value in a:
            if b_value > a_value:
                smaller = a_value
            elif b_value < a_value:
                greater = a_value
            
            if smaller and greater:
                return f"{b_value} is between {smaller} and {greater}"
    
    return "There is no such combination"

a = [1, 4, 12]
b = [2, 13]
print(get_between(a, b))

这种情况下的输出将为 2 is between 1 and 4,但您可以根据需要调整 return 值。

也许有一些我没有理解的微妙之处,但除非我弄错了,否则您只需要检查元素是否在 aminmax 之间。这与 a 中的元素是否排序无关,或者 b 中的值是否必须介于 a 中的连续值之间。只要它们在 minmax 之间, 就必须 成为 a 中的“段”,这些值在。

>>> a = [1, 4, 12]
>>> b = [2, 13]
>>> n, m = min(a), max(a)
>>> [n < x < m for x in b]
[True, False]

当然,前提是 (a) 您不需要 之间的哪个 个数字,并且 (b) 如果不是 [=15= 中的所有值] 必须在同一区间内。

如果您认为我遗漏了什么,请发表评论。

如果你不太关心性能,这里有一个pythonic解决方案-

def betwn(rangelist, valuelist):
    # Get list of all ranges between each consecutive number of rangelist
    rgs = [range(rangelist[n], rangelist[n + 1]) for n in range(len(rangelist) - 1)]
    # A function to check whether a given element exists between 2 consecutive numbers of rangelist
    verifyfunc = lambda e: any(e in r for r in rgs)
    # Return the qualifying elements from valuelist
    return [e for e in valuelist if verifyfunc(e)]

输出

>>> betwn([1, 4, 12], [2, 13])
[2]