[英]How to sort a list in python based on another list
I have a python list with user ids data = [123,456,789]
and I want to sort this list based on how many points they have (calculated by points[userid]).我有一个 python 列表,其中用户 ID
data = [123,456,789]
,我想根据他们有多少点(由点 [userid] 计算)对这个列表进行排序。 I have tried SortedData = sorted(data,key=points,reverse=True)
to no avail.我试过
SortedData = sorted(data,key=points,reverse=True)
无济于事。 Is there any way to do this?有没有办法做到这一点?
Thanks.谢谢。 Evan
埃文
You need to epxlicit it in a lambda
.您需要在
lambda
中将其显式化。 You could di points[x]
but points.get(x,0)
may be safer here你可以 di
points[x]
但points.get(x,0)
在这里可能更安全
data = [123,456,789]
points = {123:20, 456:10, 789:15}
sortedData = sorted(data, key=lambda x:points.get(x,0), reverse=True)
print(sortedData)
If you're ok of letting None
as default value instead of a number, you can reduce to如果你可以让
None
作为默认值而不是数字,你可以减少到
sortedData = sorted(data, key=points.get, reverse=True) # use the method itself
key
also accepts a function. key
还接受 function。
Try this:尝试这个:
sorted_list = list(sorted(data, key= lambda userid: points[userid], reverse=True))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.