我想从iterable中检索特定索引。这相当于:
In [7]: def f():
...: return [1,2,3,4,5]
In [8]: (_, x, _, y, _) = f()
In [9]: x, y
Out[9]: (2, 4)
但是我不想多次计算iterable,或者它很长,我也不想写太多的_
我的问题纯粹是出于好奇,我实际上使用了一个局部变量,如上图所示。你知道吗
编辑:
一种解决方案是使用带有符号iterable[start:end:step]
的切片:
In [24]: (x, y) = f()[1:4:2]
In [25]: x, y
Out[25]: (2, 4)`
EDDIT BIS公司:
如果您需要检索iterable中的每一个n
元素,使用切片是可行的,但是如果您想要索引2,3
和5,6
处的元素,使用operator.itemgetter(2,3,5,6)(lst)
似乎是更好的解决方案:
In [8]: operator.itemgetter(2,3,5,6)(range(10))
Out[8]: (2, 3, 5, 6)
一种稍微迂回的方法是使用来自
operator
模块的itemgetter
函数。你知道吗对
itemgetter
的调用创建了一个callable,它接受一个iterableL
,并返回L[2]
和L[3]
。你知道吗相关问题 更多 >
编程相关推荐