我有两个清单
a = [1, 4, 12]
b = [2, 13]
我想知道中的值list b
是否介于中的两个值之间,list a
因此,在这种情况下,2 将介于 1 和 4 之间。13 不会介于任何数字之间。
我已经尝试过bisect
功能,但我无法让它工作。我能够将它与单个值和一个列表一起使用,但不能与两个列表一起使用。
也许有一些我没有得到的微妙之处,但除非我弄错了,否则你只需要检查元素是否在 themin
和max
from之间a
。这与 in 中的元素是否a
已排序,或者 from 的值是否b
必须在 from 的连续值之间无关a
。只要它们在min
和之间max
,就必须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)如果不是所有值b
都必须在相同的区间内。
如果您认为我遗漏了什么,请发表评论。
这实际上取决于您希望它返回什么。我编写了一个代码,它将返回它找到的第一个模式,但是通过一些更改,我确信返回所有组合并不难。
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
,但您可以将返回值调整为您想要的任何值。
如果您不太关心性能,这里有一个 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]
您可以保留两个运行索引以获取介于值之间的所有元素的列表:
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]