python - Custom sort order of list -
i have lists such as:
mylist1 = ['alpha', 'green'] mylist2 = ['blue', 'alpha', 'red']
i want sort these 2 lists custom ordered list: ['red','blue','green','alpha']
so mylist1 = ['green', 'alpha']
, mylist2 = ['red','blue','alpha']
how can in python?
demonstration:
>>> mylist1 = ['alpha', 'green'] >>> mylist2 = ['blue', 'alpha', 'red'] >>> sort_order = ['red', 'blue', 'green', 'alpha'] >>> mylist1.sort(key=sort_order.index) >>> mylist1 ['green', 'alpha'] >>> mylist2.sort(key=sort_order.index) >>> mylist2 ['red', 'blue', 'alpha']
explanation:
the key
parameter in list.sort
causes list determine order comparing key(element)
instead of element
. example, case-insensitive sort, can pass key
function makes string lowercase. lowercase elements compared, original elements preserved:
>>> x = ["age", "bonkers", "cheese"] >>> x.sort() >>> x ['bonkers', 'age', 'cheese'] >>> str.lower("bonkers") 'bonkers' >>> x.sort(key=str.lower) >>> x ['age', 'bonkers', 'cheese']
using sort_order.index
key uses index element has in sort_order
list determine order instead of element itself. 'red'
uses 0
, 'blue'
uses 1
, etc... result list sorted gets sorted according each element in sort_order
.
Comments
Post a Comment