python - 按长度对列表列表进行排序时跟踪原始索引

标签 python list sorting nested-lists

您可以按如下方式对列表的列表进行排序:

l1 = [1,2,3]
l2 = [1,2,3]
l3 = [1,2]
lists = [l1, l2, l3]
sorted_lists = sorted(lists, key=len)
print sorted_lists  #[[1,2], [1,2,3], [1,2,3]]

我不知道如何跟踪索引,然后将 sorted_lists 的内容与原始列表名称 l1l2l3

This接近,但我不确定按长度排序时如何实现解决方案。

最佳答案

很有可能。只需稍微修改键即可指定要应用 len 的正确谓词。

>>> lists = [l1, l2, l3]
>>> lists = sorted(enumerate(lists), key=lambda x: len(x[1])) # enumerate is a tuple of (index, elem), sort by len(elem)
[(2, [1, 2]), (0, [1, 2, 3]), (1, [1, 2, 3])]

关于python - 按长度对列表列表进行排序时跟踪原始索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44687057/

相关文章:

list - 在 Haskell 中配对相邻列表项

c++ - 返回链表中的最大值

python - 如何在 Python 中使用 OpenCV SortIdx()?

php - MySQL 中的排序/

python - 对列表的一部分进行就地排序

python - 狮身人面像快速启动失败

c# - 如何返回另一个列表中三个最低值的列表

mysql - 如何对 var length ids(复合字符串+数字)进行排序?

Python - 将 Fabric 与 Sudo 结合使用

python - 在 python 中,对于标量,math.acos() 是否比 numpy.arccos() 快?