我有一个排序列表,一个范围包含多个列表:
>>> n= [10, 20, 30, 40]
>>> m= [[1, 20], [21, 30]]
我要做的是检查n
列表中的所有元素是否在m
中的任何现有范围内。例如,根据以上示例,40不在任何范围内。
我试图在下面的帖子中扩展问题的答案,但似乎不起作用。
Checking if all elements of a List of Lists are in another List of Lists Python
is_there = set(tuple(x) for x in [n]).issubset(tuple(x) for x in m)
答案 0 :(得分:5)
您应该遍历n
中的每个元素,并检查它是否在m
的每个列表的范围内。假设您只使用int:
[any(x in range(r[0], r[1]) for r in m) for x in n]
如果要包括范围的末尾,只需添加1:
[any(x in range(r[0], r[1]+1) for r in m) for x in n]
答案 1 :(得分:3)
简单的方法是检查所有元素:
items = [10, 20, 30, 40]
ranges = [[1, 20], [21, 30]]
result = all(any(low <= i <= high for low, high in ranges) for i in items)
为了娱乐,您可以通过使用实际的range
对象来使收容检查有所不同:
range_objects = [range(low, high + 1) for low, high in ranges]
filtered_items = all(any(i in r for r in range_objects) for i in items)
如果您想获得匹配的物品:
good = [i for i in items if any(low <= i <= high for low, high in ranges)]
您还可以获取不良元素:
bad = [i for i in items if all(i < low or i > high for low, high in ranges)]
那样,您的原始结果仅为not bad
。
答案 2 :(得分:1)
由于您说的是“排序列表” ,因此可以使用以下逻辑min
和max
。如果outside
中的任何元素超出给定范围,则True
将为n
。如果所有元素均不在范围内,则为False
n= [10, 20, 30, 40] # < as per you, this is sorted
m= [[1,20], [21,30]]
outside = any([(min(n) < i[0] and max(n)> i[1]) for i in m])
# True
编辑在下面的评论中回答@Peter DeGlopper提出的测试用例
m = [[1, 20], [31, 40]]
n = [10, 20, 25, 30, 40]
outside = any([(l < i < r for i in n) for l, r in m])
# True