我想根据 ip 地址对我的结果数组进行排序

艾什-

如何根据ip?对结果数组进行排序

当我打印结果时,我得到了这个:

[{'abc.example.com': {'hostname': 'abc.example.com', 'ip': '11.123.30.116', 'country': 'Netherlands', 'cname': ''}},      
 {'accountstat.example.com': {'hostname': 'accountstat.example.com', 'ip': '11.123.30.133', 'country': 'Netherlands', 'cname': ''}}, 
 {'ae.example.com': {'hostname': 'ae.example.com', 'ip': '11.123.24.22', 'country': 'Netherlands', 'cname': 'site.example.com'}}]
奇克

如果您希望它们按值排序,您可以将它们转换为整数并进行比较。

def ip_to_int(ip):
  return  int.from_bytes(bytes([int(part) for part in ip.split('.')]), byteorder='big')

data = [{'abc.example.com': {'hostname': 'abc.example.com', 'ip': '11.123.30.116', 'country': 'Netherlands', 'cname': ''}},
        {'accountstat.example.com': {'hostname': 'accountstat.example.com', 'ip': '11.123.30.133', 'country': 'Netherlands', 'cname': ''}}, 
        {'ae.example.com': {'hostname': 'ae.example.com', 'ip': '11.123.24.22', 'country': 'Netherlands', 'cname': 'site.example.com'}}]

sorted(data, key=lambda x: ip_to_int(list(x.values())[0]['ip']))

请注意,此解决方案仅适用于 IPv4,并且data列表中的每个项目只有一个 IP 如果您还需要 IPv6 支持,您必须首先决定如何对 IPv4 与 IPv6 进行排序,然后相应地更新ip_to_int功能。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章