简体   繁体   中英

Python: sort list based on item and external key

I have a list as follows:

[['a', 123], ['b', 456], ['c', 789]]

and the string cba

I would like to sort the list based on the first item and the order in which the string cba is in:

[['c', 789], ['b', 456], ['a', 123]]

What would be the best way to go about this?

This works quite well with key -based use of list.sort / sorted :

mylist = [['a', 123], ['b', 456], ['c', 789]]
mykey = 'cba'

mylist.sort(key=lambda x: mykey.index(x[0]))

If the key string were huge, repeated index calls would be inefficient (make a dict that maps value to index in a single pass if that's an issue, eg mykeydict = {k: i for i, k in enumerate(mykey)} , then key=lambda x: mykeydict[x[0]] ), but for short to moderate lengths, the index call is cheap enough (it's only performed once per item in mylist , not for every comparison).

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