我有一个非常大的字典,有 2 亿个键。键是元组,整数作为元组的各个元素。我想搜索“查询整数”位于字典键中元组的两个整数内的键。
目前,我正在遍历所有字典键并将整数与元组的每个元素进行比较(如果它位于该范围内)。它有效,但查找每个查询的时间大约为 1-2 分钟,我需要执行大约 100 万次这样的查询。字典的例子和我写的代码如下:
示例字典:
[{ (3547237440, 3547237503) : {'state': 'seoul teukbyeolsi', 'country': 'korea (south)', 'country_code': 'kr', 'city': 'seoul'} },
{ (403044176, 403044235) : {'state': 'california', 'country': 'united states', 'country_code': 'us', 'city': 'pleasanton'} },
{ (3423161600, 3423161615) : {'state': 'kansas', 'country': 'united states', 'country_code': 'us', 'city': 'lenexa'} },
{ (3640467200, 3640467455) : {'state': 'california', 'country': 'united states', 'country_code': 'us', 'city': 'san jose'} },
{ (853650485, 853650485) : {'state': 'colorado', 'country': 'united states', 'country_code': 'us', 'city': 'arvada'} },
{ (2054872064, 2054872319) : {'state': 'tainan', 'country': 'taiwan', 'country_code': 'tw', 'city': 'tainan'} },
{ (1760399104, 1760399193) : {'state': 'texas', 'country': 'united states', 'country_code': 'us', 'city': 'dallas'} },
{ (2904302140, 2904302143) : {'state': 'iowa', 'country': 'united states', 'country_code': 'us', 'city': 'hampton'} },
{ (816078080, 816078335) : {'state': 'district of columbia', 'country': 'united states', 'country_code': 'us', 'city': 'washington'} },
{ (2061589204, 2061589207) : {'state': 'zhejiang', 'country': 'china', 'country_code': 'cn', 'city': 'hangzhou'} }]
我写的代码:
ipint=int(ipaddress.IPv4Address(ip))
for k in ip_dict.keys():
if ipint >= k[0] and ipint <= k[1]:
print(ip_dict[k]['country'], ip_dict[k]['country_code'], ip_dict[k]['state'])
其中 ip 只是 ipaddress,如“192.168.0.1”。
如果有人可以提供有关执行此任务的更有效方法的提示,我们将不胜感激。
谢谢
最佳答案
我建议您使用另一种具有良好查询复杂性的结构,例如树。
也许你可以试试我刚找到的这个库 https://pypi.org/project/rangetree/
正如他们所说,它针对查找进行了优化,但未针对插入进行优化,因此如果您需要插入一次并循环多次,应该没问题。
另一种解决方案是不使用字典而是使用列表,对其进行排序并在其上构建索引。当有查询时对该索引进行二分法(如果范围不规则,则可能不太理想,因此我更喜欢第一种解决方案)
关于python - 使用键作为元组高效循环字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54508312/