How To Get First And Last Element Of Tuple At The Same Time
I need to get the first and last dimension of an numpy.ndarray of arbitrary size. If I have shape(A) = (3,4,4,4,4,4,4,3) my first Idea would be to do result = shape(A)[0,-1] but th
Solution 1:
I don't know what's wrong about
(s[0], s[-1])
A different option is to use operator.itemgetter()
:
from operator import itemgetter
itemgetter(0, -1)(s)
I don't think this is any better, though. (It might be slightly faster if you don't count the time needed to instantiate the itemgetter
instance, which can be reused if this operation is needed often.)
Solution 2:
s = (3,4,4,4,4,4,4,3)
result = s[0], s[-1]
Solution 3:
If you are using numpy array, then you may do that
s = numpy.array([3,4,4,4,4,4,4,3])
result = s[[0,-1]]
where [0,-1]
is the index of the first and last element. It also allow more complex extraction such as s[2:4]
Post a Comment for "How To Get First And Last Element Of Tuple At The Same Time"