简体   繁体   English

Python列表排序难题

[英]Python list sorting conundrum

I have an unusual list sorting problem which I'm struggling to find a concise and efficient way of solving. 我有一个不寻常的列表排序问题,我正在努力寻找一种简洁有效的解决方法。 The problem is as follows: I have a list called indexes with each of the items in this list corresponding to an index for the second list data. 问题如下:我有一个称为索引的列表,该列表中的每个项目都对应于第二个列表数据的索引。 So for example the first number in index is zero which corresponds to the first item in the list data which is 1 and the 3 in index corresponds to 6 in the list data because that is the 6 is the 3rd item in the list data [ including 0th item ].. 因此,例如在索引中的第一个数字是零,其对应于第一项,其中为1的列表数据和3在索引对应于在列表中的数据6,因为这是图6是在列表数据中的第三项[ 包括第0项 ] ..

Now I want to organise the list data so that that they are grouped between their indexes like below: 现在,我想组织列表数据,以便将它们按如下所示的索引分组:

indexes = [ 0, 3, 6, 8, 12, 13]

data = [1, 2, 5, 6, 11, 13, 15, 23, 35, 36, 38, 41, 46]

Solution: 解:

organised_data = [ [1,2,5], [6,11,13], [15,23], [35,36,38,41], [46] ]

I've been at this for ages. 我已经很久了。

You can use slicing between consecutive indexes in a list comprehension 您可以在列表理解中的连续索引之间使用切片

>>> [data[indexes[i]:indexes[i+1]] for i in range(len(indexes)-1)]
[[1, 2, 5], [6, 11, 13], [15, 23], [35, 36, 38, 41], [46]]

Using zip : 使用zip

>>> [data[i:j] for i, j in zip(indexes, indexes[1:])]
[[1, 2, 5], [6, 11, 13], [15, 23], [35, 36, 38, 41], [46]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM