1、在python3中,sort是對於列表類型的排序函數,函數原型為:L.sort(key=None, reverse=False),該方法沒有返回值,是對列表的就地排序。
•key-- 是指用來比較的關鍵字,可以說是列表元素的一個權值。key一般用來接受一個函數(或者匿名函數),這個函數只接受一個元素,並返回其權值
•reverse-- 是否逆序排列
a = ['Google', 'Runoob', 'Taobao', 'Facebook']
a.sort() # 默認根據第一個字母排序
print(a)
a.sort(key= lambda x : x[1]) # 根據第二個字母排序
print(a)
def takeSecond(x):
return x[1]
a.sort(key=takeSecond)
print(a)
輸出:['Facebook', 'Google', 'Runoob', 'Taobao']
['Facebook', 'Taobao', 'Google', 'Runoob']
['Facebook', 'Taobao', 'Google', 'Runoob']
2、python3中sorted函數取消了對cmp的支持,sorted 可以對所有可迭代的對象進行排序操作,尤其是可以對字典進行排序,其形式為:sorted(iterable, key=None, reverse=False)。sorted函數是有返回值的。
d = {'lily':25, 'wangjun':22, 'John':25, 'Mary':19}
sorted_keys = sorted(d) # 對字典而言,默認是對keys進行排序
print(sorted_keys)
sorted_keys1 = sorted(d, key=lambda x : x[1])
print(d_new2)
d_new = sorted(d.items(), key=lambda x: x[1], reverse=True) # 根據年齡排序,返回列表形式
print(d_new)
d_new = dict(d_new) # 使用內置函數把嵌套列表轉換成字典
print(d_new)
sorted_values = sorted(d.values(), key=lambda x:x, reverse=False) # 排序值
print(sorted_values)
輸出:
['John', 'Mary', 'lily', 'wangjun']
['wangjun', 'Mary', 'lily', 'John']
[('lily', 25), ('John', 25), ('wangjun', 22), ('Mary', 19)]
{'lily': 25, 'John': 25, 'wangjun': 22, 'Mary': 19}
[19, 22, 25, 25]
3、互換字典的鍵和值
d = {'lily':25, 'wangjun':22, 'John':25, 'Mary':19}
d_new = {v:key for key,v in d.items()}
print(d_new)
輸出:{25: 'John', 22: 'wangjun', 19: 'Mary'}