📜  Python|按字典值和长度对列表列表进行排序

📅  最后修改于: 2022-05-13 01:54:32.136000             🧑  作者: Mango

Python|按字典值和长度对列表列表进行排序

在Python列表中已经多次讨论了不同类型的排序。还讨论了Python列表列表的排序。但有时,我们需要对两个参数进行排序。第一个是列表总和,下一个是它的长度。让我们讨论如何解决这类问题。

方法 #1:使用sort()两次
想到的第一种方法是使用排序函数两次的通用方法,首先是基于值,然后是基于列表的大小。

# Python code to demonstrate
# sort list of lists by value and length
# using sort() twice 
  
# initializing list 
test_list = [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]]
  
# printing the original list
print ("The original list is : " + str(test_list))
  
# using sort() twice 
# sort list of lists by value and length
test_list.sort()
test_list.sort(key = len)
  
# printing result
print ("The list after sorting by value and length " + str(test_list))
输出:


方法#2:使用 lambda函数
上面的方法调用了一个排序函数两次,但是作为对它的改进,这个方法只调用了一次排序函数,并使用 lambda函数一次性执行了两个排序。

# Python code to demonstrate
# sort list of lists by value and length
# using lambda function
  
# initializing list 
test_list = [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]]
  
# printing the original list
print ("The original list is : " + str(test_list))
  
# using lambda function 
# sort list of lists by value and length
res = sorted(test_list, key = lambda i: (len(i), i))
  
# printing result
print ("The list after sorting by value and length " + str(res))
输出: