Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing in python similar to MATLAB

In Matlab, slice can be a vector:

a = {'a','b','c','d','e','f','g'}; % cell array
b = a([1:3,5,7]);

How can I do the same thing in python?

a = ['a','b','c','d','e','f','g']
b = [a[i] for i in [0,1,2,4,6]]

but when 1:3 becomes 1:100, this will not work. Using range(2),4,6 returns ([0,1,2],4,6), not (0,1,2,4,6). Is there a fast and "pythonic" way?

like image 895
PinkyJie Avatar asked Nov 30 '22 16:11

PinkyJie


1 Answers

If you want to do things that are similar to Matlab in Python, NumPy should always be your first guess. In this case, you need numpy.r_:

from numpy import array, r_
a = array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
print a[r_[1:3, 5, 7]]

['b' 'c' 'f' 'h']
like image 191
Sven Marnach Avatar answered Dec 06 '22 01:12

Sven Marnach