Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract multiple slices in an array?

Tags:

python

I need to extract data from multiple positions in an array.

A simple array would be:-

listing = (4, 22, 24, 34, 46, 56) 

I am familiar with slicing. For instance:-

listing[0:3] 

would give me:-

(4, 22, 24) 

However I am unable to get out multiple slices. For instance:-

listing[0:3, 4:5] 

gives me

TypeError: tuple indices must be integers not tuples 

Despite Searching two Python books and the Internet I cannot work out the syntax to use.

like image 970
OldSteve Avatar asked Aug 11 '16 11:08

OldSteve


People also ask

Can you slice arrays?

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end ( end not included) where start and end represent the index of items in that array. The original array will not be modified.

How do you slice a multidimensional 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 .

Can you slice array in Python?

Array slicing can be easily done following the Python slicing method. For which the syntax is given below. Again, Python also provides a function named slice() which returns a slice object containing the indices to be sliced. The syntax for using this method is given below.

Can you slice arrays in C?

Array-slicing is supported in the print and display commands for C, C++, and Fortran.


2 Answers

You can slice twice and join them.

listing[0:3] + listing[4:5] 
like image 116
alex Avatar answered Sep 23 '22 09:09

alex


If you have the index numbers of the slices you need you can just grab them with a loop contained in a list.

index_nums = [0,2,4] output = [listing[val] for val in index_nums] 

This will return [4,24,46]

like image 45
nrc Avatar answered Sep 25 '22 09:09

nrc