![](/img/trans.png)
[英]How to find if a number in a list is in a interval of two numbers in a list?
[英]For a list of numbers and a list of intervals, find the interval in which each number is located
在字典中如下:
example = {'Chr3' : [[1, 4], [5, 10], [13, 17]]}
我如何知道區號6和15位於哪個列表中?
我可以用一個簡單的for
循環編寫一個解決方案:
for key in example.keys():
for element in example[key]:
if element[0]<= 6 <= element[1] or element[0] <= 15 <= element[1]:
print element
但在我真正的問題中,我不只有兩個數字而是一個數字列表。
那么,我在想是否有更多的pythonic方法使用特殊列表或字典方法/函數來解決這樣的問題?
編輯:由於投票率下降,我澄清說我知道如何使用另一個循環編寫代碼以獲取數字列表,我想知道是否有更好的解決方案來解決同樣的問題,更有效率!
創建一個字典,將您的數字列表中的任何數字映射到example['Chr3']
的相應間隔。
>>> {x:filter(lambda y: y[0] <= x <= y[1], example['Chr3']) for x in lst}
{6: [5, 10], 15: [13, 17]}
使用功能!
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))
[5, 10]
[13, 17]
3 [1, 4]
6 [5, 10]
11 None
15 [13, 17]
17 [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
您的代碼查找任何匹配而不是多個匹配,您可以使用any
列表comp
from itertools import chain
pot = [6, 15]
print([[a, b] for a, b in chain(*example.values()) if any(a <= i <= b for i in pot)])
[[5, 10], [13, 17]]
如果您只關心任何比賽,您只需要檢查潛在數字的最小值和最大值 :
pot = [6, 15,7,9,8]
from itertools import chain
mn,mx = min(pot), max(pot)
print([[a, b] for a, b in chain(*example.values()) if mn <= a <= mx or mn <= b <= mx])
[[5, 10], [13, 17]]
所以你現在正在不斷地檢查a
和b
而不是線性。
或者使用python3你可以使用范圍和使用in
其中是python3中的O(1)
操作:
pot = [6, 15,7,9,8]
mn ,mx = min(pot), max(pot)
inter = range(mn, mx+1)
print([[a, b] for a, b in chain(*example.values()) if a in inter or b in inter])
[[5, 10], [13, 17]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.