如何在python中高效地找到2维字典中存在的4个值之间的键值?

2024-04-18 09:31:30 发布

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

我在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-loops。在本例中,它们如下所示:

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中使用什么?你知道吗

谢谢你的帮助!你知道吗

Example Picture


Tags: 函数inforsearch字典exampledef密钥
1条回答
网友
1楼 · 发布于 2024-04-18 09:31:30

您不需要遍历随机数范围和ask 4million times for forgiveness-您使用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'}}

了解一下提供稀疏矩阵的模块可能会很有用。你知道吗

相关问题 更多 >