猿问

Python字典列表检索过程

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

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


任何帮助将不胜感激。


潇潇雨雨
浏览 179回答 3
3回答

慕的地6264312

字典不应该以这种方式使用。尽管如此,这里有一个解决方案可以解决您的问题。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:&nbsp; &nbsp; for territory, postCodes in mydict.items():&nbsp; &nbsp; &nbsp; &nbsp; if (postCodes[0] <= zipCode <= postCodes[1]):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(str(zipCode) + " is in " + territory)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break对于给定的每个邮政编码,我们会检查它是否在所有地区的邮政编码范围内。如果是,我们打印它。

慕雪6442864

我会改变mydict,所以关键是邮政编码,价值是领土。大概没有属于两个地区的邮政编码。newdict = {}for territory, zipcodes in mydict.items():&nbsp; &nbsp; for zipcode in zipcodes:&nbsp; &nbsp; &nbsp; &nbsp; newdict[zipcode] = territory现在您可以获取列表中所有邮政编码的地区for zipcode in myzips:&nbsp; &nbsp; print(zipcode, newdict.get(zipcode)请注意,在您发布的数据中,没有邮政编码在myzips中mydict,因此newdict.get将返回None。

慕桂英4014372

我在 Sri 和 Eric 的帮助下完成了这项工作。我让它工作。我刚刚为 Territory(final_list) 制作了一个不同的列表,然后遍历每个列表。h = 0while h < len(final_list) :&nbsp; &nbsp; &nbsp; &nbsp; for zipCode in myzips:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for territory, postCodes in dict.items():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (postCodes[0] <= zipCode <= postCodes[1])and postCodes[2] == final_list[h] :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mylist2.append(str(zipCode)+","+territory)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; #break&nbsp; &nbsp; &nbsp; &nbsp; h += 1&nbsp;&nbsp;
随时随地看视频慕课网APP

相关分类

Python
我要回答