给定一个数字列表和一个区间列表,找到每个数字所在的区间

2024-06-28 19:45:31 发布

您现在位置:Python中文网/ 问答频道 /正文

在字典中如下:

example = {'Chr3' : [[1, 4], [5, 10], [13, 17]]}

我怎么知道编号6和15在哪个列表间隔中?在

我可以用一个简单的for循环编写解决方案:

^{pr2}$

但在我真正的问题上,我不是只有两个数字,而是一个数字列表。在

所以,我在想,是否有一种更像python的方法来使用特殊列表或字典方法/函数来解决这个问题?在

编辑: 因为投了反对票,我澄清说我知道如何用另一个循环在上面写一个数字列表的代码,我想知道是否有更好的解决方案来解决同样的问题,一个更有效的方法!在


Tags: 方法函数代码编辑列表for间隔字典
3条回答

使用函数!在

example = {'Chr3' : [[1, 4], [5, 10], [13, 17]]}
example_nums = [3, 6, 11, 15, 17]

def find_interval(dct, num):
    for key, values in dct.items():
        for left, right in values:
            if left <= num <= right:
                return [left, right]

print(find_interval(example, 6))
print(find_interval(example, 15))

# Now you can use the function to find the interval for each number
for num in example_nums:
    print(num, find_interval(example, num))

输出

^{pr2}$

https://repl.it/Bb78/4

创建一个字典,将数字列表中的任何数字映射到example['Chr3']中的相应间隔。在

>>> {x:filter(lambda y: y[0] <= x <= y[1], example['Chr3']) for x in lst}
{6: [5, 10], 15: [13, 17]}

你能举一个更具体的例子吗?我认为你的代码可以通过在列表中加入一个循环行来工作:

for x in my list:
    for key in example.keys():
         for element in example[key]:
            if element[0]<= x <= element[1] or element[0] <= x <= element[1]:
                   print element

相关问题 更多 >