我想检查一个列表的范围是否在下一个列表的范围内,这是一个例子:
pos = [[50, 100], [50, 200], [250, 1500], [300, 2000], [300, 3300]]
Run Code Online (Sandbox Code Playgroud)
正如我们在这里看到的那样,在(包括在)pos[0]的范围内,与with 和with 相同.pos[1][50, 100][50, 200]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
Run Code Online (Sandbox Code Playgroud)
它看起来很难看,任何人都可以提出另一个解决方案吗?
编辑:
正如@MKesper建议的那样,我还应该使用循环遍历列表条目(并且可能获得每个位置的True/False列表).
你知道的范围[a,b]是在一个范围内[c,d]给出的c <= a和b <= d(因此a,b被夹之间c,d或c <= a < b <= d,但我们认为a < b反正总是成立).所以你可以简单地使用:
def in_list(pos,i):
a,b = pos[i]
c,d = pos[i+1]
return c <= a and b <= d
Run Code Online (Sandbox Code Playgroud)
如果您要检查有任何这样的情况下,你可以使用:
any(in_list(pos,i) for i in range(len(pos)-1))
Run Code Online (Sandbox Code Playgroud)