有這么個需求,獲取一堆ip,想排個序。發現直接使用sorted排序得不到想要的結果,因為sorted默認是按照字符(ascll碼)排序的。那么就拿出來今天的主角:
Python list內置sort()方法用來排序,也可以用python內置的全局sorted()方法來對可迭代的序列排序生成新的序列。
從python2.4開始,list.sort()和sorted()函數增加了key參數來指定一個函數,此函數將在每個元素比較前被調用。
#!/usr/bin/python
# -*- coding: utf-8 -*-
#創建一個list
iplist=['192.168.1.1','192.168.1.21','192.168.1.150']
#使用普通排序
ip=sorted(iplist)
print ip
#使用參數排序
ip=sorted(iplist,key=lambda s:int(s.split('.')[3]))
print ip
運行結果