一个关于排序的问题,请各位大佬赐教

2020-08-19 16:41:41 +08:00
 duyuyouci
data_list = [{1: "1"}, {3: "3"}, {4: "4"}, {10: "10"}, {7: "7"}, {6: "6"}],
类似这样的数据,怎么用 sort 去排序,sort 里的 key 关键字参数要怎么写
2079 次点击
所在节点    Python
16 条回复
Akikiki
2020-08-19 16:48:37 +08:00
data_list.sort(key=lambda x: x.keys()[0])
duyuyouci
2020-08-19 16:53:05 +08:00
@Akikiki 会报错的,TypeError: 'dict_keys' object is not subscriptable
h272377502
2020-08-19 16:54:00 +08:00
就假设你的字典都是一个 key,sorted(data_list, key=lambda k: list(k.keys())[0])
duyuyouci
2020-08-19 16:58:15 +08:00
@h272377502 对呀,转化一下类型就好了,厉害
Akikiki
2020-08-19 17:04:19 +08:00
@duyuyouci 哦 你是 python3 吧
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'}]
lithbitren
2020-08-21 09:21:50 +08:00
data_list.sort(key=lambda x: next(iter(x)))

不转 list 也可以实现
yucongo
2020-08-21 14:57:38 +08:00
sorted(data_list, key=lambda x: [*x])
duyuyouci
2020-08-21 16:42:37 +08:00
@yucongo 这个好像不行,顺序没有变
duyuyouci
2020-08-21 16:42:45 +08:00
@lithbitren 高级
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, 顺序怎么没有变呢
yucongo
2020-08-21 19:40:57 +08:00
或( in-place ):
data_list.sort(key=lambda x: [*x])
duyuyouci
2020-08-22 09:44:33 +08:00
@yucongo 哦,sorted 是创建了一个副本,我打印的原列表,哈哈,高级,但是这个语法不太懂,老哥能解释吗
lithbitren
2020-08-22 10:53:02 +08:00
@duyuyouci

[*x]相当于[i for i in x],也相当于 list(x)

他这个一行其实可以直接写成 data_list.sort(key=list),本质还是转数组
duyuyouci
2020-08-22 11:48:36 +08:00
@lithbitren 原来如此,受教了
yucongo
2020-08-22 16:03:21 +08:00
对啊,key=list 就行了……
那么可以来一个最短的:)
sorted(data_list, key=set)

data_list.sort(key=set)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/699668

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX