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

如何在Python中对IP地址进行排序?请求协助处理指定排序需求

Sorting IP Addresses in Python as Per Your Required Order

Got it, let's figure out how to sort your IP list to match the desired output. Looking at your input and expected result, the sorting rule is:

  • First sort by the third octet of the IP address (the number after the second dot)
  • Then, for IPs with the same third octet, sort by the second octet (the number after the first dot)

Here's a straightforward way to implement this in Python:

Solution Code

# Your original input list
ip_list = [{'host': u'10.219.1.1'}, {'host': u'10.91.1.1'}, {'host': u'10.219.4.1'}, {'host': u'10.91.4.1'}]

# Define a custom key function for sorting
def ip_sort_key(item):
    # Split the IP string into octets and convert to integers
    octets = tuple(map(int, item['host'].split('.')))
    # Return a tuple that defines our sorting priority: third octet → second octet → first → fourth
    return (octets[2], octets[1], octets[0], octets[3])

# Apply the sort
sorted_ip_list = sorted(ip_list, key=ip_sort_key)

# Verify the result
print(sorted_ip_list)

Output

When you run this code, you'll get exactly the expected output:

[{'host': u'10.91.1.1'}, {'host': u'10.219.1.1'}, {'host': u'10.91.4.1'}, {'host': u'10.219.4.1'}]

How It Works

  • We split each IP string into its four components (octets) using split('.'), then convert them to integers to ensure numeric sorting (instead of lexicographical sorting, which would incorrectly treat "219" as smaller than "91" because "2" comes before "9" alphabetically).
  • The key tuple (octets[2], octets[1], octets[0], octets[3]) tells Python to first sort by the third octet (index 2), then the second (index 1), followed by the first and fourth octets. These last two don't affect your specific case but make the sort robust for other IP variations.

内容的提问来源于stack exchange,提问作者Sujith Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 10:37:28