Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 对元组列表进行排序_Python_Sorting_Tuples - Fatal编程技术网

Python 对元组列表进行排序

Python 对元组列表进行排序,python,sorting,tuples,Python,Sorting,Tuples,我有一个元组列表,我想根据另一个列表中指定的顺序进行排序。这是要排序的列表: Start_Keyword=[(u'NUMBER', u'two', u'2.0', [1]), (u'RND', u'random', u'random', [8])] 所需输出为: Start_Keyword=[(u'RND', u'random', u'random', [8]),(u'NUMBER', u'two', u'2.0', [1])] 我所做的是定义一个顺序,并根据其索引进行排序: predef

我有一个元组列表,我想根据另一个列表中指定的顺序进行排序。这是要排序的列表:

Start_Keyword=[(u'NUMBER', u'two', u'2.0', [1]), (u'RND', u'random', u'random', [8])]
所需输出为:

Start_Keyword=[(u'RND', u'random', u'random', [8]),(u'NUMBER', u'two', u'2.0', [1])] 
我所做的是定义一个顺序,并根据其索引进行排序:

predefined_list = ['PROB','RND','NUMBER']
ordering = {word: i for i, word in enumerate(predefined_list)}
print sorted(Start_Keyword, key=lambda x: ordering.get)
但我得到了以下错误:

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

有人能帮上忙吗?

这是一种让它工作的方法:

lst = sorted(Start_Keyword, key=lambda x: predefined_list.index(x[0]))
print(lst)
使用
预定义列表中的索引作为排序标准

你好像在用蟒蛇2;在python3中,您版本的错误消息更为清晰:

TypeError: unorderable types: 
    builtin_function_or_method() < builtin_function_or_method()
TypeError:无序类型:
内置函数或方法()

您尝试比较
dict
get
方法(不带参数)。它们确实是无序的。

这是一种让它们正常工作的方法:

lst = sorted(Start_Keyword, key=lambda x: predefined_list.index(x[0]))
print(lst)
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]) )
使用
预定义列表中的索引作为排序标准

你好像在用蟒蛇2;在python3中,您版本的错误消息更为清晰:

TypeError: unorderable types: 
    builtin_function_or_method() < builtin_function_or_method()
TypeError:无序类型:
内置函数或方法()

您尝试比较
dict
get
方法(不带参数)。它们确实是无序的。

不使用此代码。不使用此代码。
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]) )