[英]Pythonic way to create sublists from a list of indices
I would like to know an elegant way to create smaller lists from a list with indexes in this way:我想知道一种优雅的方法来以这种方式从具有索引的列表中创建较小的列表:
My list:我的列表:
lst= [ 0, 1, 5, 0, 3, 7, 1, 3, 9, 1, 0]
My indexes:我的索引:
index_list=[2, 5 ,8]
I got the indexes by finding the peaks, now I would like it to create sub lists between these peaks.我通过查找峰值获得了索引,现在我希望它在这些峰值之间创建子列表。
So I expect this in return:所以我希望得到这样的回报:
returned_list = [[0,1,5], [0,3,7], [1,3,9], [1, 0]]
I am trying something like this:我正在尝试这样的事情:
def sublist(lst, index): def 子列表(lst,索引):
tmplst = []
list_of_list = []
for j in range(len(index)):
for i in range(len(lst)):
if index[j] > lst[i]:
tmplst.append(lst[i])
Please let me know what I can do.请让我知道我能做什么。
Let's try zip
with list comprehension:让我们尝试使用列表理解的zip
:
[a[x+1:y+1] for x,y in zip([-1] + index_list, index_list + [len(a)])]
Output: Output:
[[0, 1, 5], [0, 3, 7], [1, 3, 9], [1, 0]]
The indices that you are using in your index_list
are not very pythonic to begin with, because they do not comply with the indexing conventions employed by slicing in python.您在index_list
中使用的索引一开始就不是很pythonic,因为它们不符合 python 中切片所采用的索引约定。
So let's start by correcting this:所以让我们从纠正这个开始:
index_list = [index + 1 for index in index_list]
Having done that, we can use slice
to obtain the necessary slices.完成后,我们可以使用slice
来获取必要的切片。 None
is used to signify the start or end of the list. None
用于表示列表的开始或结束。
[lst[slice(start, end)] for start, end in zip([None] + index_list,
index_list + [None])]
As you tagged your question with numpy
possible answer is:当您用numpy
标记您的问题时,可能的答案是:
import numpy as np
lst = [ 0, 1, 5, 0, 3, 7, 1, 3, 9, 1, 0]
index_list = [2, 5 ,8]
index_list = [i+1 for i in index_list] # in python indices are starting with 0
arrays_list = np.split(lst, index_list)
returned_list = list(map(list,arrays_list))
print(returned_list)
Output: Output:
[[0, 1, 5], [0, 3, 7], [1, 3, 9], [1, 0]]
Not sure if pythonic, but numpy
has a built in function for that不确定是否 pythonic,但numpy
有一个内置的 function
import numpy as np
lst = [0, 1, 5, 0, 3, 7, 1, 3, 9, 1, 0]
index_list = [el + 1 for el in [2, 5, 8]]
resp = np.split(lst, index_list, axis=0)
print(resp)
lst= [ 0, 1, 5, 0, 3, 7, 1, 3, 9, 1, 0]
index_list=[2, 5 ,8,11]
index_lst2 = [slice(x -2, x +1) for x in index_list]
returned_list = [lst[index] for index in index_lst2]
print(returned_list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.