方法一:
ip_list = ['192.168.1.100', '192.168.10.3', '192.168.8.1'] ip_list.sort(lambda x,y: cmp(''.join( [ i.rjust(3, '0') for i in x.split('.')] ), ''.join( [ i.rjust(3, '0') for i in y.split('.')] ) ) )
结果
['192.168.1.100', '192.168.8.1', '192.168.10.3']
方法二:
转换成 int 型,用 int 来比较
import struct import socket def ip2int(addr): return struct.unpack("!I", socket.inet_aton(addr))[0] def int2ip(addr): return socket.inet_ntoa(struct.pack("!I", addr)) ip_list = ['192.168.1.100', '192.168.10.3', '192.168.8.1'] # 构建 int_ip:ip 形式的 key:value, 并对 key 排序 ip_unsorted_dict = {} for ip in ip_list: int_ip = ip2int(ip) ip_unsorted_dict[int_ip] = ip keys = ip_unsorted_dict.keys() keys.sort() ip_sorted_list=[] for key in keys: ip_sorted_list.append(ip_unsorted_dict[key]) print ip_sorted_list
结果:
['192.168.1.100', '192.168.8.1', '192.168.10.3']
参考:
http://blog.csdn.net/hong201/article/details/3119519
Leave a Reply