如何使用2个条件属性对python列表进行排序 [英] How to sort a python list using 2 conditional attributes
问题描述
让我们说我要对看起来像这样的列表进行排序:
Lets say I want to sort a list that looks like this:
arr = ['45621', '78124', '24613']
上面的列表存储了公司中各个员工的ID.我不想仅根据ID进行排序,而是使用以下字典基于与ID对应的属性进行排序:
The above list stores the IDs for various employees at a company. I don't want to sort based on the IDs alone, but based on attributes that correspond to the IDs, using the following dictionary:
employees = {
'45621' : { 'rating' : 3, 'hours_worked' : 42 },
'78124' : { 'rating' : 4, 'hours_worked' : 78 },
'24613' : { 'rating' : 3, 'hours_worked' : 51 }
}
所以它是这样的:如果雇员的rating
较高,则他/她的ID将排在第一位.但是,如果有2名员工具有相同的rating
,则我们将hours_worked
进行比较,那么工作更多的人将排在其他人之前.
So its something like this: if an employee has a higher rating
, his/her ID will come first. However, if 2 employees have the same rating
, then we compare the hours_worked
, and whoever has worked more will come before the other.
现在,我正在考虑2种不同的排序方法:插入和合并.我从网上编辑了一些代码示例,但是我正在努力比较第二个条件,即算法的2个等级相等.例如,我的插入排序的编辑版本如下所示:
Right now, I am thinking about 2 different sorting methods: insertion, and merge. I edited a few code samples from the web, but I am struggling to compare the second condition, that is, when 2 ratings are equal for the algorithms. For instance, the edited versions of my insertion sort looks like this:
InsertionSort
def insertionSort(arr):
for i in range(1, len(arr)):
key = employees[ arr[i] ]['rating']
j = i-1
# Falls apart after this part
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
合并排序似乎更加复杂,但是我试图至少理解一个问题.
The merge sort seems even more complex, but I am trying to at least understand one to get an idea.
对这些排序方法的任何帮助将不胜感激.谢谢.
Any help with these sorting methods will be greatly appreciated. Thanks.
注意:我不想使用内置的排序机制,因为这主要是为了学习,所以不是重复的.
Note: I don't want to use a built in sorting mechanism, as this is mainly for learning, so it is not a duplicate.
推荐答案
您可以基于自定义键使用python list.sort
或sorted
:
You can use python list.sort
or sorted
based on a custom key:
arr = ['45621', '78124', '24613']
employees = {
'45621' : { 'rating' : 3, 'hours_worked' : 42 },
'78124' : { 'rating' : 4, 'hours_worked' : 78 },
'24613' : { 'rating' : 3, 'hours_worked' : 51 }
}
arr.sort(key=lambda x: (employees[x]["rating"], employees[x]["hours_worked"]))
print(arr)
结果:
['45621', '24613', '78124']
此外,由于您首先需要价格更高的轮胎,因此您应该颠倒顺序.
Also, since you need the ones with higher ranting first, you should reverse the order.
arr.sort(key=lambda x: (employees[x]["rating"], employees[x]["hours_worked"]), reverse=True)
这里有一个在线示例
这篇关于如何使用2个条件属性对python列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!