如何按自定义函数对列表进行排序?

2024-04-26 07:07:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做我的小“家庭作业”。我想用一个我定义的函数对列表进行排序。你知道吗

用于实验

list = [[1], [1,2,3,4,5,6,7], [1,2,3], [1,2], [1,2,3,4], [1,2,3,4,5,6,7,8]]
function1: (the length of every small list) / 10
function2: (the length of every small list) / 12
and the first 3 lists judged by function1, and the other by function2

我想要的结果是:

list = [[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7]]

我已经可以排序列表的长度没有功能,所以请让我知道如果你有任何想法。 谢谢!你知道吗


Tags: andofthe函数列表by定义排序
1条回答
网友
1楼 · 发布于 2024-04-26 07:07:16

您可以使用内置的sorted()函数来实现它。通过提供一个附加函数作为key,您可以指定iterable元素的排序方式。这里您希望按元素的长度(即内部列表的长度)排序,因此可以使用内置的len()函数。还可以实现自定义lambda函数。你知道吗

alist = [[1], [1,2,3,4], [1,2], [1,2,3,4,5,6,7], [1,2,3], [1,2,3,4,5,6,7,8]]
sorted_list = sorted(alist, key=len)
print(sorted_list)

输出:

[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7, 8]]

相关问题 更多 >