>>> from operator import itemgetter
>>> a = range(100)
>>> itemgetter(5,13,25)(a)
(5, 13, 25)
Answer from John La Rooy on Stack Overflow>>> from operator import itemgetter
>>> a = range(100)
>>> itemgetter(5,13,25)(a)
(5, 13, 25)
If you are a Matlab user, but want to use Python, check out numpy:
In [37]: import numpy as np
In [38]: a = np.arange(100)
In [39]: s = a[[5,13,25]]
In [40]: s
Out[40]: array([ 5, 13, 25])
Here is a comparison of NumPy and Matlab, and here is a table of common Matlab commands and their equivalents in NumPy.
I was going through crash course and was learning slicing and i tried
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
it gave me ['charles', 'martina', 'michael']
shouldnt it give me ['michael', 'florence', 'eli']?
First, note that indexing in Python begins at 0. So the indices you need will be [0, 2].
You can then use a list comprehension:
temp = ['a', 'b', 'c', 'd']
idx = [0, 2]
res = [temp[i] for i in idx] # ['a', 'c']
With built-ins, you may find map performs better:
res = map(temp.__getitem__, idx) # ['a', 'c']
Since you are using Python 2.7, this returns a list. For Python 3.x, you would need to pass the map object to list.
If you are looking to avoid a Python-level loop altogether, you may wish to use a 3rd party library such as NumPy:
import numpy as np
temp = np.array(['a', 'b', 'c', 'd'])
res = temp[idx]
# array(['a', 'c'],
# dtype='<U1')
res2 = np.delete(temp, idx)
# array(['b', 'd'],
# dtype='<U1')
This returns a NumPy array, which you can then be converted to a list via res.tolist().
Use this :
temp = ['a','b','c','d']
temp[0:4:2]
#Output
['a', 'c']
Here first value is starting index number which is (Included) second value is ending index number which is (Excluded) and third value is (steps) to be taken.
Happy Learning...:)