[英]How to efficient find existent key-values of 2-dimensional dictionary in python which are between 4 values?
我在Python中有一個小問題。 我有一個二維字典。 現在將其稱為dict [x,y]。 x和y是整數。 我嘗試僅選擇在4點之間匹配的鍵對值。 函數應如下所示:
def search(topleft_x, topleft_y, bottomright_x, bottomright_y):
For example: search(20, 40, 200000000, 300000000)
Now are Dictionary-items should be returned that match to:
20 < x < 20000000000
AND 40 < y < 30000000000
未設置此巨大矩陣中的大多數鍵對值(請參見圖片-這就是為什么我不能僅進行迭代)。
此函數應返回一個簡短的字典。 在圖片所示的示例中,它將是一個帶有3個綠色圓圈值的新字典。 有沒有簡單的解決方案來實現這一目標? 我最近使用2 for循環。 在此示例中,它們將如下所示:
def search():
for x in range(20, 2000000000):
for y in range(40, 3000000000):
try:
#Do something
except:
#Well item just doesnt exist
當然,這是非常低效的。 所以我的問題是:如何在Python中增強這一簡單的功能? 在C#中,我使用Linq來處理類似的事情...在python中使用什么?
感謝幫助!
您不會遍歷隨機數范圍並請求四百萬次寬恕 -您使用2個數域來指定“過濾器”,並且僅遍歷字典中屬於這些范圍的現有鍵:
# get fancy on filtering if you like, I used explicit conditions and continues for clearity
def search(d:dict,r1:range, r2:range)->dict:
d2 = {}
for x in d: # only use existing keys in d - not 20k that might be in
if x not in r1: # skip it - not in range r1
continue
d2[x] = {}
for y in d[x]: # only use existing keys in d[x] - not 20k that might be in
if y not in r2: # skip it - not in range r2
continue
d2[x][y] = "found: " + d[x][y][:] # take it, its in both ranges
return d2
d = {}
d[20] = {99: "20",999: "200",9999: "2000",99999: "20000",}
d[9999] = { 70:"70",700:"700",7000:"7000",70000:"70000"}
print(search(d,range(10,30), range(40,9000)))
輸出:
{20: {99: 'found: 20', 999: 'found: 200'}}
看看提供稀疏矩陣的模塊可能會很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.