[英]Python: Sort list of lists by size (reversed) and store the original indices
basically a combination of this:基本上是这样的组合:
[x[0] for x in sorted(MYLIST, key=len, reverse=True)]
[x[0] for x in sorted(MYLIST, key=lambda i: i[1])]
If we say that lst_of_lst
is the original list,如果我们说
lst_of_lst
是原始列表,
sorted_lst = [(len(lst), lst) for lst in lst_of_lst]
sorted_lst = sorted(sorted_lst, reverse = True)
sorted_lst = [lst for (length,lst) in sorted_lst]
sorted_lst
is the new sorted list. sorted_lst
是新的排序列表。
However, this code may not work depending on how you want to treat cases where two lists have the same length.但是,此代码可能不起作用,具体取决于您希望如何处理两个列表具有相同长度的情况。
Because sorted
and enumerate
are iterators, it's not really possible to get the effect you want using them together in a single loop.因为
sorted
和enumerate
是迭代器,所以在单个循环中使用它们真的不可能获得您想要的效果。 So, instead we gather the info you want seperately.因此,我们会单独收集您想要的信息。
nested_lists = [
[1, 2, 3, 4, 5],
[1, 2],
[1, 2, 3],
[1, 2, 3, 4]
]
# Capture original indices
indexed_lists = [(index, sublist) for index, sublist in enumerate(nested_lists)]
# sort them by length of sublist
sorted_lists = sorted(indexed_lists, reverse=True, key=lambda item: len(item[1]))
# Iterate over the sorted object, printing the old and new indexes
for new_index, (old_index, sublist) in enumerate(sorted_lists):
print('old index:', old_index, 'new_index:', new_index)
print(sublist, end='\n\n')
The output would be in reverse length order (largest to smallest) printing the old and new indices like this:输出将以相反的长度顺序(从大到小)打印旧索引和新索引,如下所示:
old index: 0 new_index: 0
[1, 2, 3, 4, 5]
old index: 3 new_index: 1
[1, 2, 3, 4]
old index: 2 new_index: 2
[1, 2, 3]
old index: 1 new_index: 3
[1, 2]
You can use sorted
in conjunction with enumerate
and provide the method with the key
and the reverse
parameters.您可以将
sorted
与enumerate
结合使用,并为该方法提供key
和reverse
参数。 Below, lst
is sorted by length, then reversed.下面,
lst
按长度排序,然后反转。
For example, if you have a list like so:例如,如果您有这样的列表:
lst = [[29,53,27], [34,34,76,23,65], [32,39]]
You can use sorted
and enumerate
in a one liner:您可以在一行中使用
sorted
和enumerate
:
sorted_lst = sorted(enumerate(lst), key=lambda v: len(v[1]), reverse=True)
Which returns a list of tuples with the original index position as the first value and the list as the second value:它返回一个元组列表,原始索引位置作为第一个值,列表作为第二个值:
[(1, [34, 34, 76, 23, 65]), (0, [29, 53, 27]), (2, [32, 39])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.