按第一项对嵌套列表进行排序-itemgetter不能胜任

按第一项对嵌套列表进行排序-itemgetter不能胜任,第1张

按第一项对嵌套列表进行排序-itemgetter不能胜任

更改键以将字符串转换为int会有所帮助,这也是其他一些排序技巧。

from operator import itemgetterlist_to_sort=[('89372', 2), ('89373', 1), ('89374', 1), ('89375', 1), ('89376', 1),     ('89377', 1), ('228055', 1), ('228054', 1), ('228057', 2), ('228056', 1), ('228051', 1), ('228050', 1),('228053', 1), ('203184', 6), ('228059', 1), ('228058', 1), ('89370', 2), ('89371', 3), ('89372', 2), ('89373', 1), ('89374', 1), ('89375', 1), ('89376', 1), ('89377', 1)]print list_to_sortlist_to_sort.sort()print list_to_sort # badly sorted as describedlist_to_sort.sort(key=itemgetter(0))print list_to_sort # badly sorted as described (same as above)list_to_sort.sort(key=lambda x: int(x[0]))print list_to_sort # sorted welllist_to_sort.sort(key=lambda x: int(x[0]), reverse=True)print list_to_sort # sorted well in reverse

关于构建要从字典排序的列表的旁注

iteritems()
是执行以下 *** 作的更好方法

dict_List = [(x, FID_GC_dict[x]) for x in FID_GC_dict.keys()]dict_List = [(k,v) for k,v in FID_GC_dict.iteritems()]


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5617640.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存