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.
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.
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 .
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.
Array-slicing is supported in the print and display commands for C, C++, and Fortran.
You can slice twice and join them.
listing[0:3] + listing[4:5]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With