Python 检查列表范围是否在另一个列表范围内

Python 检查列表范围是否在另一个列表范围内,python,list,Python,List,我想检查列表的某个范围是否在下一个列表的范围内,下面是一个示例: pos = [[50, 100], [50, 200], [250, 1500], [300, 2000], [300, 3300]] 正如我们在这里看到的,pos[0]在pos[1]的范围内([50100]包含在[50200]中),对于pos[2]和pos[3]以及pos[4]和pos[5],情况也是如此 为此,我创建了一个返回布尔值的函数: def in_list(i): # index of the list if

我想检查列表的某个范围是否在下一个列表的范围内,下面是一个示例:

pos = [[50, 100], [50, 200], [250, 1500], [300, 2000], [300, 3300]]
正如我们在这里看到的,
pos[0]
pos[1]
的范围内(
[50100]
包含在
[50200]
中),对于
pos[2]
pos[3]
以及
pos[4]
pos[5]
,情况也是如此

为此,我创建了一个返回布尔值的函数:

def in_list(i): # index of the list
    if i < len(pos)-2 and pos[i][0] >= pos[i+1][0] and pos[i][0] <= pos[i+1][1] 
    and pos[i][1] >= pos[i+1][0] and pos[i][1] <= pos[i+1][1]:
        return True
    else:
        return False
列表中的定义(i):#列表的索引
如果i=pos[i+1][0]和pos[i][0]=pos[i+1][0]和pos[i][1]您知道范围
[a,b]
[c,d]
给定的
c压缩/交错列表及其移位副本,然后检查之前的项目是否包含在该范围内

在所有元素上计算一个线性:

pos = [[50, 100], [50, 200], [250, 1500], [300, 2000], [300, 3300]]

result = [all(x1 <= a  <= y1 for a in t) for t,(x1,y1) in zip(pos,pos[1:])]


print(result)
(结果当然少了1项:最后一项不合格/未测试)

可能
all
是过度杀伤力,因为只有2个值需要测试,所以可以选择:

result = [x1 <= x0 <= y1 and x1 <= y0 <= y1  for (x0,y0),(x1,y1) in zip(pos,pos[1:])]

结果=[x1对于pos:
@MKesper中的条目,您可能想用
对列表条目进行迭代:
@MKesper,是的,您是对的。也许您也可以将
pos
作为函数的参数。这并不是真正需要的,但访问globals并不是一个好的做法。@mseifer:的确如此。因为在最初的问题
pos
中有一个范围这太宽泛了。@WillemVanOnsem谢谢你,但是为什么
any(in_list(pos,2)for i in range(len(pos)-1))
返回
False
?@Bilal:因为你用
2
调用了
in_list(pos,2)
。所以这里只检查
[250,1500]
是否在
[300,2000]
中,这不是因为
[250299]
不在
[3002000]
中,因为我喜欢一行程序(我通常不太喜欢它们),这很难理解。不过它可能很快。我的替代方案可能更好,因为它不使用
所有的
:少一个gencomp
pos = [[50, 100], [50, 200], [250, 1500], [300, 2000], [300, 3300]]

result = [all(x1 <= a  <= y1 for a in t) for t,(x1,y1) in zip(pos,pos[1:])]


print(result)
[True, False, False, True]
result = [x1 <= x0 <= y1 and x1 <= y0 <= y1  for (x0,y0),(x1,y1) in zip(pos,pos[1:])]