You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按IP地址对results数组进行排序?附示例输出

按IP地址对results数组排序的实现方法

没问题,要给这个results数组按IP地址排序其实不难,不过得先处理下IP的格式——直接按字符串排序IP会出逻辑错误(比如11.123.24.22字符串排序会比11.123.30.116靠后,但实际IP段里24比30小,应该排在前面)。

思路分析

你的数组结构有点特殊:每个元素是只包含一个键的字典,这个键对应的值里才存着ip字段。所以排序的核心是:

  1. 从每个元素里提取出ip字符串;
  2. 将IP字符串转换成可正确排序的格式(整数元组);
  3. 用Python的sorted()函数,通过自定义排序规则完成排序。

代码实现

首先先把你的原始数据定义好:

results = [
    {'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'}}
]

方法1:用自定义函数清晰实现

这种方式可读性更强,适合新手理解:

def get_ip_key(item):
    # 取出字典里的唯一值(因为每个元素是单键字典)
    host_details = next(iter(item.values()))
    # 把IP拆分成四段,转成整数元组(这样排序时会按IP逻辑比较)
    ip_components = tuple(map(int, host_details['ip'].split('.')))
    return ip_components

# 执行排序
sorted_results = sorted(results, key=get_ip_key)

# 打印排序后的结果
for entry in sorted_results:
    print(entry)

方法2:用lambda表达式简化

如果追求代码简洁,可以把逻辑压缩到一行:

sorted_results = sorted(
    results,
    key=lambda x: tuple(map(int, next(iter(x.values()))['ip'].split('.')))
)

排序后的输出结果

运行代码后,你会得到按IP从小到大排序的数组:

{'ae.example.com': {'hostname': 'ae.example.com', 'ip': '11.123.24.22', 'country': 'Netherlands', 'cname': 'site.example.com'}}
{'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': ''}}

为什么这样可行?

把IP字符串转成(int, int, int, int)的元组后,Python会按元组的每个元素依次比较:先比第一段IP,相同再比第二段,以此类推,完全符合IP地址的排序逻辑,避免了字符串排序的坑。

内容的提问来源于stack exchange,提问作者Aaish -

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:28:33