简体   繁体   中英

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]). I have tried SortedData = sorted(data,key=points,reverse=True) to no avail. Is there any way to do this?

Thanks. Evan

You need to epxlicit it in a lambda . You could di points[x] but points.get(x,0) may be safer here

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

sortedData = sorted(data, key=points.get, reverse=True) # use the method itself 

key also accepts a function.

Try this:

sorted_list = list(sorted(data, key= lambda userid: points[userid], reverse=True))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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