解包特定索引

2024-04-19 21:47:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从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,35,6处的元素,使用operator.itemgetter(2,3,5,6)(lst)似乎是更好的解决方案:

In [8]: operator.itemgetter(2,3,5,6)(range(10))
Out[8]: (2, 3, 5, 6)

Tags: in元素编辑returndef符号切片解决方案
1条回答
网友
1楼 · 发布于 2024-04-19 21:47:55

一种稍微迂回的方法是使用来自operator模块的itemgetter函数。你知道吗

 import operator
 m = operator.itemgetter(2,3)
 x, y = m([1,2,3,4,5])

itemgetter的调用创建了一个callable,它接受一个iterable L,并返回L[2]L[3]。你知道吗

相关问题 更多 >