1
Akikiki 2020-08-19 16:48:37 +08:00
data_list.sort(key=lambda x: x.keys()[0])
|
2
duyuyouci OP @Akikiki 会报错的,TypeError: 'dict_keys' object is not subscriptable
|
3
h272377502 2020-08-19 16:54:00 +08:00
就假设你的字典都是一个 key,sorted(data_list, key=lambda k: list(k.keys())[0])
|
4
duyuyouci OP @h272377502 对呀,转化一下类型就好了,厉害
|
6
mahonejolla 2020-08-19 17:05:37 +08:00
data_list = [{1: "1"}, {3: "3"}, {4: "4"}, {10: "10"}, {7: "7"}, {6: "6"}]
kk = data_list.sort(key=lambda x: list(x.keys())[0]) print(data_list) # [{1: '1'}, {3: '3'}, {4: '4'}, {6: '6'}, {7: '7'}, {10: '10'}] kk = sorted(data_list, key=lambda k: list(k.keys())[0]) print(kk) # [{1: '1'}, {3: '3'}, {4: '4'}, {6: '6'}, {7: '7'}, {10: '10'}] |
7
lithbitren 2020-08-21 09:21:50 +08:00
data_list.sort(key=lambda x: next(iter(x)))
不转 list 也可以实现 |
8
yucongo 2020-08-21 14:57:38 +08:00 via Android
sorted(data_list, key=lambda x: [*x])
|
10
duyuyouci OP @lithbitren 高级
|
11
yucongo 2020-08-21 19:31:49 +08:00
In [43]: data_list = [{1: "1"}, {3: "3"}, {4: "4"}, {10: "10"}, {7: "7"}, {6: "6"}]
In [44]: sorted(data_list, key=lambda x: [*x]) Out[44]: [{1: '1'}, {3: '3'}, {4: '4'}, {6: '6'}, {7: '7'}, {10: '10'}] 完全用你的数据,python3.6, 顺序怎么没有变呢 |
12
yucongo 2020-08-21 19:40:57 +08:00
或( in-place ):
data_list.sort(key=lambda x: [*x]) |
13
duyuyouci OP @yucongo 哦,sorted 是创建了一个副本,我打印的原列表,哈哈,高级,但是这个语法不太懂,老哥能解释吗
|
14
lithbitren 2020-08-22 10:53:02 +08:00
|
15
duyuyouci OP @lithbitren 原来如此,受教了
|
16
yucongo 2020-08-22 16:03:21 +08:00
对啊,key=list 就行了……
那么可以来一个最短的:) sorted(data_list, key=set) 或 data_list.sort(key=set) |