【问题标题】:Python dictionary list retrieval processPython字典列表检索过程
【发布时间】:2020-07-23 17:55:09
【问题描述】:

我一直在努力解决一个涉及基于每个区域内的开始范围和结束范围的区域的邮政编码的问题。我似乎无法弄清楚如何使用下面的字典来浏览我的邮政编码列表。最终我需要一个列表,上面写着邮政编码 6015 属于区域 A

mydict = {'Territory a': [60000,60999], 'Territory b': [90000,90999], 'Territory c': [70000,700999]}
myzips = [60015,60016,60017,90001,90002,90003,76550,76556,76557]

我研究了如何调用字典中的值,但我没有看到调用键的好方法,在我的例子中是区域描述。我并不完全相信字典是要走的路,但我想不出另一种方式,所有元素都保持在一起以便在未来的函数或循环中被调用。

任何帮助将不胜感激。

【问题讨论】:

    标签: python dictionary arraylist list-comprehension


    【解决方案1】:

    字典不应该以这种方式使用。尽管如此,这里有一个解决方案可以解决您的问题。

    mydict={'Territory a':[60000,60999],'Territory b': [90000,90999],'Territory c': [70000,70099]}
    myzips =[60015,60016,60017,90001,90002,90003,76550,76556,76557]
    
    for zipCode in myzips:
        for territory, postCodes in mydict.items():
            if (postCodes[0] <= zipCode <= postCodes[1]):
                print(str(zipCode) + " is in " + territory)
                break
    

    对于每个给定的邮编,我们会检查它是否在所有地区的邮政编码范围内。如果是,我们打印它。

    【讨论】:

    • 或者,您可以使用postCodes[0] &lt;= zip &lt;= postCodes[1],这应该会更快一些。此外,您可能希望使用与 zip 不同的变量名称,因为它是一个内置函数。
    • 更新了帖子!谢谢
    【解决方案2】:

    我会更改mydict,所以键是邮政编码,值是领土。大概没有属于两个地区的邮政编码。

    newdict = {}
    for territory, zipcodes in mydict.items():
        for zipcode in zipcodes:
            newdict[zipcode] = territory
    

    现在您可以获取列表中所有邮政编码的地区

    for zipcode in myzips:
        print(zipcode, newdict.get(zipcode)
    

    请注意,在您发布的数据中,myzips 中的邮政编码均不在mydict 中,因此newdict.get 将返回None

    【讨论】:

    • 您需要考虑邮政编码的范围。虽然他将 Territory a 列为 60000、60999,但他也希望它们之间的所有值。我认为在这种情况下反转 key:val 将不起作用,因为它只会检查边界值。
    • 感谢 Eric 和 Sri 的帮助。这对我的代码有很大帮助。关于“大概没有属于两个地区的邮政编码”,实际上发生了许多重叠。当我输入代码时,它会先进行第一个匹配,然后继续进行而不考虑其他匹配。我想我需要一个 while 循环,但不确定。
    【解决方案3】:

    我在 Sri 和 Eric 的帮助下完成了这项工作。 我让它工作。我刚刚为 Territory(final_list) 制作了一个不同的列表,然后遍历每个列表。

    h = 0
    while h < len(final_list) :
    
            for zipCode in myzips:
                for territory, postCodes in dict.items():
                    if (postCodes[0] <= zipCode <= postCodes[1])and postCodes[2] == final_list[h] :
                        mylist2.append(str(zipCode)+","+territory)
                    #break
            h += 1  
    

    【讨论】:

      猜你喜欢
      • 2022-11-10
      • 2012-01-29
      • 1970-01-01
      • 2021-11-21
      • 2022-11-12
      • 2018-02-06
      • 2023-03-23
      相关资源
      最近更新 更多