Python|按子列表的大小对列表列表进行排序
给定一个列表列表,任务是根据子列表的大小对列表进行排序。让我们讨论一些方法来做同样的事情。方法#1:使用排序
Python3
# Python code to demonstrate
# sort list of list
# on the basis of size of sublist
ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4],
[1, 2, 3, 4, 5], [2, 4, 6]]
# printing initial ini_list
print ("initial list", str(ini_list))
# sorting on basis of size of list
ini_list.sort(key = len)
# printing final result
print("final list", str(ini_list))
Python3
# Python code to demonstrate
# sort list of list
# on the basis of size of sublist
ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4],
[1, 2, 3, 4, 5], [2, 4, 6]]
# printing initial ini_list
print ("initial list", str(ini_list))
# sorting on basis of size of list
ini_list.sort(key = lambda x:len(x))
# printing final result
print("final list", str(ini_list))
Python3
# Python code to demonstrate
# sort list of list
# on the basis of size of sublist
ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4],
[1, 2, 3, 4, 5], [2, 4, 6]]
# printing initial ini_list
print ("initial list", str(ini_list))
# sorting on basis of size of list
result = sorted(ini_list, key = len)
# printing final result
print("final list", str(result))
输出:初始列表 [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] 最终列表 [[1, 2], [1, 2, 3], [2, 4, 6], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
方法 #2:使用 lambda
Python3
# Python code to demonstrate
# sort list of list
# on the basis of size of sublist
ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4],
[1, 2, 3, 4, 5], [2, 4, 6]]
# printing initial ini_list
print ("initial list", str(ini_list))
# sorting on basis of size of list
ini_list.sort(key = lambda x:len(x))
# printing final result
print("final list", str(ini_list))
输出:初始列表 [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] 最终列表 [[1, 2], [1, 2, 3], [2, 4, 6], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
方法#3:使用排序
Python3
# Python code to demonstrate
# sort list of list
# on the basis of size of sublist
ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4],
[1, 2, 3, 4, 5], [2, 4, 6]]
# printing initial ini_list
print ("initial list", str(ini_list))
# sorting on basis of size of list
result = sorted(ini_list, key = len)
# printing final result
print("final list", str(result))
输出:初始列表 [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] 最终列表 [[1, 2], [1, 2, 3], [2, 4, 6], [1, 2, 3, 4], [1, 2, 3, 4, 5]]