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)
输出:
[['z', 2], 
 ['y', 4], 
 ['y', 2], 
 ['y', 1], 
 ['x', 5], 
 ['x', 2]]
预期输出:
[['z', 2], 
 ['y', 1], 
 ['y', 2], 
 ['y', 4], 
 ['x', 2], 
 ['x', 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]
| 归档时间: | 
 | 
| 查看次数: | 1077 次 | 
| 最近记录: |