Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stepping with multiple values while slicing an array in Python

I am trying to get m values while stepping through every n elements of an array. For example, for m = 2 and n = 5, and given

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

I want to retrieve

b = [1, 2, 6, 7] 

Is there a way to do this using slicing? I can do this using a nested list comprehension, but I was wondering if there was a way to do this using the indices only. For reference, the list comprehension way is:

 b = [k for j in [a[i:i+2] for i in range(0,len(a),5)] for k in j] 
like image 569
Paul W Avatar asked Jun 01 '18 15:06

Paul W


People also ask

What does [- 1 :] mean in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.

How do you slice an element in an array in Python?

To slice elements from two-dimensional arrays, you need to specify both a row index and a column index as [row_index, column_index] . For example, you can use the index [1,2] to query the element at the second row, third column in precip_2002_2013 .

What is difference between indexing and slicing in Python?

What are Indexing and Slicing? Indexing: Indexing is used to obtain individual elements. Slicing: Slicing is used to obtain a sequence of elements. Indexing and Slicing can be be done in Python Sequences types like list, string, tuple, range objects.


1 Answers

I agree with wim that you can't do it with just slicing. But you can do it with just one list comprehension:

>>> [x for i,x in enumerate(a) if i%n < m] [1, 2, 6, 7] 
like image 154
Kevin Avatar answered Sep 24 '22 19:09

Kevin