How to get the first and last element of a tuple at the same time

I need to get the first and last dimension of 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 it result = shape(A)[0,-1], but that doesn't seem to work with tuples, why not?

Is there an easier way to do this than

s=shape(A)
result=(s[0], s[-1])

Thanks for any help

+5
source share
3 answers

I don't know what happened to

(s[0], s[-1])

Another option is to use operator.itemgetter():

from operator import itemgetter
itemgetter(0, -1)(s)

I do not think this is better. (This can be a little faster if you do not count the time required to create an instance itemgetterthat can be reused if this operation is often required.)

+11
s = (3,4,4,4,4,4,4,3)
result = s[0], s[-1]
+5

numpy,

s = numpy.array([3,4,4,4,4,4,4,3])
result = s[[0,-1]]

[0,-1] - . , s[2:4]

+1

All Articles