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?
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']
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