Python 如何根据列表的数值对其进行排序?
我有一本字典,数据结构如下:Python 如何根据列表的数值对其进行排序?,python,python-3.x,list,sorting,dictionary,Python,Python 3.x,List,Sorting,Dictionary,我有一本字典,数据结构如下: d = {'TRANSFERRED': [2281, 1031, 1775, 867, 1242], 'CLOSED': [239, 269, 645, 540, 388], 'DEFERRED': [89, 5, 68, 48, 37], 'OPEN': [3, 0, 2, 1, 0], 'IN PROGRESS': [0, 2, 4, 0, 5], 'QUEUED': [
d = {'TRANSFERRED': [2281, 1031, 1775, 867, 1242],
'CLOSED': [239, 269, 645, 540, 388],
'DEFERRED': [89, 5, 68, 48, 37],
'OPEN': [3, 0, 2, 1, 0],
'IN PROGRESS': [0, 2, 4, 0, 5],
'QUEUED': [0, 0, 0, 0, 0]}
字典包含带有数值的列表,我想根据其数值的总和对它们进行排序,如下所示:
d = {'TRANSFERRED': [2281, 1031, 1775, 867, 1242], # sum gives 7196
'CLOSED': [239, 269, 645, 540, 388], # sum gives 2081
'DEFERRED': [89, 5, 68, 48, 37], # sum gives 247
'IN PROGRESS': [0, 2, 4, 0, 5], # sum gives 11
'OPEN': [3, 0, 2, 1, 0], # sum gives 6
'QUEUED': [0, 0, 0, 0, 0]} # sum gives 0
如您所见,新字典是根据每个列表的数值总和从高到低排序的。我一直在使用以下技巧对包含单个项的列表的字典进行排序,例如:
d2 = {'TRANSFERRED': [-2281],
'CLOSED': [239],
'DEFERRED': [489],
'OPEN': [34],
'IN PROGRESS': [0],
'QUEUED': [-10]}
sorted(d2.items(), key=lambda x: x[1], reverse=True)
我想复制这个相同的结果,但基于字典中每个列表的值之和。我怎样才能达到这个目标?请随意使用以下链接。欢迎反馈或评论以改进此问题。您只需对当前方法进行一次更改-从
键
函数返回一个和
:
sorted(d2.items(), key=lambda x: sum(x[1]), reverse=True)
# ^change ^
演示:
您只需对当前方法进行一次更改-从
键
函数返回一个和
:
sorted(d2.items(), key=lambda x: sum(x[1]), reverse=True)
# ^change ^
演示:
排序(d2.items(),key=lambda x:sum(x[1]),reverse=True)
?排序(d2.items(),key=lambda x:sum(x[1]),reverse=True)
?
#you can solve this problem using sort and sum functions.
# original list.
d = {'TRANSFERRED': [2281, 1031, 1775, 867, 1242],
'CLOSED': [239, 269, 645, 540, 388],
'DEFERRED': [89, 5, 68, 48, 37],
'OPEN': [3, 0, 2, 1, 0],
'IN PROGRESS': [0, 2, 4, 0, 5],
'QUEUED': [0, 0, 0, 0, 0]}
#function to calculate the sum of a list
def list_sum(t):
return sum(t[1])
# we can not sort dict. directly so we have to make the dict into list of tuples
# were key will be the first element and value will be the second element.
# will become 'TRANSFERRED': [2281, 1031, 1775, 867, 1242]
# ( 'TRANSFERRED', [2281, 1031, 1775, 867, 1242])
# t0 = 'TRANSFERRED'
# t1 = [2281, 1031, 1775, 867, 1242]
# sorted function will sorted the list of tuples based on the result
# generated by the list_sum function
result = sorted(d.items(),key=list_sum,reverse=True)
print(result)