如何通过嵌套列表的值和仅嵌套列表的第一个值的reverse=True条件对列表的python列表进行排序?

Jit*_*dra 1 python sorting python-3.x

我试图按嵌套列表的值对此列表进行排序,但我只想要按相反顺序排列的字母位置和按升序排列的数字。

sample_list = [
  ['y', 4], 
  ['x', 2], 
  ['y', 1], 
  ['z', 2], 
  ['x', 5], 
  ['y', 2]]

sorted_list = sorted(sample_list, key=lambda nested: (nested[0], nested[1]), reverse=True)
Run Code Online (Sandbox Code Playgroud)

输出:

[['z', 2], 
 ['y', 4], 
 ['y', 2], 
 ['y', 1], 
 ['x', 5], 
 ['x', 2]]
Run Code Online (Sandbox Code Playgroud)

预期输出:

[['z', 2], 
 ['y', 1], 
 ['y', 2], 
 ['y', 4], 
 ['x', 2], 
 ['x', 5]]
Run Code Online (Sandbox Code Playgroud)

abc*_*abc 5

您可以-nested[1]在 lambda 函数中使用。

>>> sorted_list = sorted(sample_list, key=lambda nested: (nested[0],-nested[1]), reverse=True)
>>> print(*sorted_list,sep='\n')                                                                   
['z', 2]
['y', 1]
['y', 2]
['y', 4]
['x', 2]
['x', 5]
Run Code Online (Sandbox Code Playgroud)