如何同时获取元组的第一个和最后一个元素 [英] How to get first AND last element of tuple at the same time

查看:61
本文介绍了如何同时获取元组的第一个和最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取任意大小的numpy.ndarray的第一个和最后一个维度.

I need to get the first and last dimension of an numpy.ndarray of arbitrary size.

如果我有 shape(A)=(3,4,4,4,4,4,4,3)我的第一个想法是做 result = shape(A)[0,-1] ,但这似乎不适用于元组,为什么不这样做?

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 that doesn't seem to work with tuples, why not ??

有没有比这更整洁的方式

Is there a neater way of doing this than

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

感谢您的帮助

推荐答案

我不知道这是怎么回事

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

另一种选择是使用 operator.itemgetter():

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

不过,我认为这没有什么更好的.(如果您不计算实例化 itemgetter 实例所需的时间,它可能会稍快一些,如果经常需要执行此操作,则可以重用该实例.)

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.)

这篇关于如何同时获取元组的第一个和最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆