如何在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
相关产品推荐
相关产品推荐

