繁体   English   中英

如何使用数字和字母字符串对字典列表进行排序?

[英]How to sort a list of dicts with numeric and alphabetic strings?

我需要帮助来对我的听写列表进行排序。

my_list = [{'id': 1, 'code': '2'}, {'id': 2, 'code': 'b'}, {'id': 3, 'code': '1'}, {'id': 4, 'code': '10'}, {'id': 5, 'code': 'a'}]

import operator
my_list.sort(key=operator.itemgetter('code'))

结果:

[{'id': 3, 'code': '1'}, {'id': 4, 'code': '10'}, {'id': 1, 'code': '2'}, {'id': 5, 'code': 'a'}, {'id': 2, 'code': 'b'}]

我想像这样对列表进行排序:

[{'id': 3, 'code': '1'}, {'id': 1, 'code': '2'}, {'id': 4, 'code': '10'}, {'id': 5, 'code': 'a'}, {'id': 2, 'code': 'b'}]

我没有看到对它进行排序的答案。

您需要将数字字符串转换为int (或float ),以便排序不是数字字符串上的字典。 一种简单的方法是将自定义排序 function 定义为:

def custom_sort(x):
    try:
        return 0, float(x)
    except ValueError:
        return 1, x

my_list.sort(key= lambda x: custom_sort(x['code']))

print(my_list)

[{'id': 3, 'code': '1'},
 {'id': 1, 'code': '2'},
 {'id': 4, 'code': '10'},
 {'id': 5, 'code': 'a'},
 {'id': 2, 'code': 'b'}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM