简体   繁体   English

使用索引Python手动切片列表

[英]Manual slicing of a list using their indices, Python

Minimal example 最小的例子

I have a list a = [10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,....,] 我有一个列表a = [10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,....,]

I want to get a new list new_list = [40,50,60,100,110,120,...] , ie append fourth, fifth and sixth value, skip next three, append next three and so on. 我想得到一个新列表new_list = [40,50,60,100,110,120,...] ,即追加第四,第五和第六个值,跳过下三个,追加下三个,依此类推。

My idea is to create a list called index : 我的想法是创建一个名为index的列表:

index = [3,4,5,9,10,11,...] new_list = [a[i] for i in index] # This should give me what I want

but how do I create the list index ? 但是如何创建列表index I know np.arange has the step option, but that is only for spacing between values. 我知道np.arange有step选项,但这只是值之间的间距。

Here's one way - 这是一种方式 -

[a[i] for i in range(len(a)) if i%6>=3]

Sample run - 样品运行 -

In [49]: a = [10,20,30,40,50,60,70,80,90,100,110,120,130,140,150]

In [50]: [a[i] for i in range(len(a)) if i%6>=3]
Out[50]: [40, 50, 60, 100, 110, 120]

Here's an improved and faster version using Python built-in function enumerate building up on Divakar's nice logic . 这是一个改进的,更快的版本,使用Python内置函数enumerate构建Divakar的好逻辑

In [4]: lst = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150]
In [6]: [item for idx, item in enumerate(lst) if idx%6 >= 3]
Out[6]: [40, 50, 60, 100, 110, 120]

why is this version better & preferable? 为什么这个版本更好,更可取?

In [10]: lst = range(10, 100000, 10)       

In [11]: %timeit [lst[idx] for idx in range(len(lst)) if idx % 6 >= 3]
1.1 ms ± 22.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [12]: %timeit [item for idx, item in enumerate(lst) if idx % 6 >= 3]
788 µs ± 8.67 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

That's more than 300 microseconds gain! 这超过300微秒的增益! Furthermore, enumerate() is more straightforward and intuitive (cf loop like a native ) 此外, enumerate()更直接和直观( 比如本机循环

You can generate the index elements of continuous 3 increment and repeat of 3 elements 您可以生成连续3个增量和3个元素重复的索引元素

a = np.asarray([10,20,30,40,50,60,70,80,90,100,110,120,130,140,150])
b = np.tile(np.arange(1,4),int(len(a)/6)+1) + np.repeat(np.arange(3,int(len(a)/2)+3,3),3)
a.take(b)

Out: 日期:

array([ 50,  60,  70,  80,  90, 100, 110, 120, 130])

Explanation 说明

np.tile(np.arange(1,4),int(len(a)/6)+1)
#array([1, 2, 3, 1, 2, 3, 1, 2, 3])

np.repeat(np.arange(3,int(len(a)/2)+3,3),3)
#array([3, 3, 3, 6, 6, 6, 9, 9, 9])

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

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