简体   繁体   中英

Sort a Tuple List Python

I have a tuple list in which i want to sort according to the order specified in another list. This is the list to be sorted:

Start_Keyword=[(u'NUMBER', u'two', u'2.0', [1]), (u'RND', u'random', u'random', [8])]

The required output is :

Start_Keyword=[(u'RND', u'random', u'random', [8]),(u'NUMBER', u'two', u'2.0', [1])] 

What i did is defined an order and sorted according to the index of it:

predefined_list = ['PROB','RND','NUMBER']
ordering = {word: i for i, word in enumerate(predefined_list)}
print sorted(Start_Keyword, key=lambda x: ordering.get)

But i am getting the following error:

 print sorted(Start_Keyword2, key=ordering.get)
 TypeError: unhashable type: 'list'

please can anyone help on this?

this is one way to get that working:

lst = sorted(Start_Keyword, key=lambda x: predefined_list.index(x[0]))
print(lst)

use the index in predefined_list as sort criterion.

you seem to use python2; in python3 the error message for your version is a bit clearer:

TypeError: unorderable types: 
    builtin_function_or_method() < builtin_function_or_method()

you try to compare the get method (without arguments) of dict . they are indeed unorderable.

predefined_list = ['PROB','RND','NUMBER']
Start_Keyword=[(u'NUMBER', u'two', u'2.0', [1]), (u'RND', u'random', u'random', [8])]    

order = {word:index for index, word in enumerate(predefined_list)}
Start_Keyword.sort(key=lambda x: order.get(x[0]) )

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