a_list=[
{'status':'f','name':'battery','time':1.3},
{'status':'a','name':'mouse','time':3.5},
{'status':'p','name':'battery','time':1.0},
{'status':'p','name':'battery','time':0.8},
{'status':'n','name':'touch','time':1.6},
{'status':'t','name':'typec','time':1.7},
{'status':'fail','name':'keyboard','time':3.4},
{'status':'fail','name':'keyboard','time':1.7},
{'status':'fa','name':'mouse','time':1.8},
{'status':'k','name':'touch','time':2.4}]
我想得到的结果是:我想在字典中放入相同的名称。然后根据时间排序。 结果如下:
sorted=[
{'status':'f','name':'battery','time':0.8},{'status':'f','name':'battery','time':1.0},
{'status':'p','name':'battery','time':1.3},{'status':'n','name':'touch','time':1.6,
{'status':'k','name':'touch','time':2.4},{'status':'fail','name':'keyboard','time':1.7},
{'status':'fail','name':'keyboard','time':3.4},{'status':'fa','name':'mouse','time':1.8},
{'status':'a','name':'mouse','time':3.5}{'status':'t','name':'typec','time':1.7}]
答案 0 :(得分:0)
您需要按name
和time
对其进行排序:
unsorted=[{'status':'f','name':'battery','time':1.3},
{'status':'a','name':'mouse','time':3.5},{'status':'p','name':'battery','time':1.0},
{'status':'p','name':'battery','time':0.8},{'status':'n','name':'touch','time':1.6},
{'status':'t','name':'typec','time':1.7},{'status':'fail','name':'keyboard','time':3.4},
{'status':'fail','name':'keyboard','time':1.7},{'status':'fa','name':'mouse','time':1.8},
{'status':'k','name':'touch','time':2.4}]
sorted(unsorted, key=lambda x: (x['name'], x['time']))
#[{'status': 'p', 'name': 'battery', 'time': 0.8}, {'status': 'p', 'name': 'battery', 'time': 1.0}, {'status': 'f', 'name': 'battery', 'time': 1.3}, {'status': 'fail', 'name': 'keyboard', 'time': 1.7}, {'status': 'fail', 'name': 'keyboard', 'time': 3.4}, {'status': 'fa', 'name': 'mouse', 'time': 1.8}, {'status': 'a', 'name': 'mouse', 'time': 3.5}, {'status': 'n', 'name': 'touch', 'time': 1.6}, {'status': 'k', 'name': 'touch', 'time': 2.4}, {'status': 't', 'name': 'typec', 'time': 1.7}]