【问题标题】:How to efficient find existent key-values of 2-dimensional dictionary in python which are between 4 values?python - 如何在python中有效地找到4个值之间的二维字典的现有键值?
【发布时间】:2018-08-02 21:17:13
【问题描述】:

我在 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

【问题讨论】:

  • 请问你能举一个字典的例子吗?我不明白为什么你需要用for x in range(20, 2000000000):尝试每个值
  • @roganjosh 感谢您的回答。因为如果我做这么多循环,程序太慢了!在二维字典中,这就像 6e+19 循环 ^^
  • 我刚刚看到您的完整回复。这和我问的一点关系都没有。我很清楚这个问题,我要求你提供一个示例输入。了解如何创建Minimal, Complete and Verifiable example

标签: python python-2.7 dictionary key


【解决方案1】:

您不会遍历随机数字范围和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'}}

看看提供稀疏矩阵的模块可能会很有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多