1. 程式人生 > >python———sort、sorted使用(對dict排序)

python———sort、sorted使用(對dict排序)

一、L.sort(cmp=None,key=None,reverse=False)對L原地排序不會返回新的L
sort使用:
1、key引數定義

L=[{2:8,3:5},{1:8,2:5,3:6,4:7},{1:5,2:9,3:6}]
def f(x):
    return len(L)
L.sort(key=f)
print(L)

結果:
[{2: 8, 3: 5}, {1: 5, 2: 9, 3: 6}, {1: 8, 2: 5, 3: 6, 4: 7}]

2、cmp引數定義【注意:python3裡沒有cmp引數】

L=[{2:8,3:5},{1:8,2:5,3:6,4:7
},{1:5,2:9,3:6}] def f(a,b): return a[2]-b[2] L.sort(cmp=f) print L

結果:[{1: 8, 2: 5, 3: 6, 4: 7}, {2: 8, 3: 5}, {1: 5, 2: 9, 3: 6}]

二、sorted(L, cmp=None, key=None, reverse=False)對data排序返回一個新的L
1、key引數定義

L=[{2:8,3:5},{1:8,2:5,3:6,4:7},{1:5,2:9,3:6}]
def f(x):
    return len(L)
print(sorted(L,key=f))

結果:
[{2: 8, 3: 5}, {1: 5, 2: 9, 3: 6}, {1: 8, 2: 5, 3: 6, 4: 7}]

2、cmp引數定義【注意:python3裡沒有cmp引數】

L=[{2:8,3:5},{1:8,2:5,3:6,4:7},{1:5,2:9,3:6}]
def f(a,b):
    return a[2]-b[2]
print sorted(L,cmp=f)

三、dict排序【根據值排序,這裡根據值的長度進行排序】

dict1={"a":["s","sd","d"],"b":["s",5],"c":[1,5,6,4]}
list1=[[len(v[1]),v[0]]
for v in dict1.items()] list1.sort() for k in list1: key=k[1] value=dict1[key] print key+"---"+str(value)

結果:
b—[’s’, 5]
a—[’s’, ‘sd’, ‘d’]
c—[1, 5, 6, 4]