Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.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
在Python3中,如何首先按降序并同时按字母顺序对元组列表进行排序?_Python_Sorting_Python 3.x - Fatal编程技术网

在Python3中,如何首先按降序并同时按字母顺序对元组列表进行排序?

在Python3中,如何首先按降序并同时按字母顺序对元组列表进行排序?,python,sorting,python-3.x,Python,Sorting,Python 3.x,如果我有一个元组列表,其中第一个是数字,第二个是字符串,例如: [(2, 'eye'), (4, 'tail'), (1, 'scarf'), (4,'voice')] ['tail', 'voice', 'eye', scarf'] 如何按数字降序排序?如果在任何一点上有一个并列数字,则具有相同数字的单词应按字母顺序进行子排序。并返回最后排序的单词 从我的例子来看: [(2, 'eye'), (4, 'tail'), (1, 'scarf'), (4,'voice')] ['tail',

如果我有一个元组列表,其中第一个是数字,第二个是字符串,例如:

[(2, 'eye'), (4, 'tail'), (1, 'scarf'), (4,'voice')]
['tail', 'voice', 'eye', scarf']
如何按数字降序排序?如果在任何一点上有一个并列数字,则具有相同数字的单词应按字母顺序进行子排序。并返回最后排序的单词

从我的例子来看:

[(2, 'eye'), (4, 'tail'), (1, 'scarf'), (4,'voice')]
['tail', 'voice', 'eye', scarf']
我按降序排列,但我不知道如何按字母顺序细分。我很乐意听到任何提示和回答。谢谢

def sorting(list)
   my_list = []
   for x, y in list.items():
     my_list+=[(y,x)]
   sort=sorted(my_list, reverse=True)

您可以使用
参数,将数字(第一个元素)移动到其负计数器部分,并按升序对列表进行排序。范例-

In [21]: lst = [(2, 'eye'), (4, 'tail'), (1, 'scarf'), (4,'voice')]

In [22]: sorted(lst, key = lambda x: (-x[0],x[1]))
Out[22]: [(4, 'tail'), (4, 'voice'), (2, 'eye'), (1, 'scarf')]
要仅获取按该顺序排列的单词列表,可以使用列表理解-

In [24]: [x[1] for x in sorted(lst, key = lambda x: (-x[0],x[1]))]
Out[24]: ['tail', 'voice', 'eye', 'scarf']

文档中回答了各种排序问题,还显示了使用“key”参数的惯用方法。