【发布时间】:2017-06-19 10:04:22
【问题描述】:
我在问这个问题:
Access multiple elements of list knowing their index
基本上,如果您有一个列表并且想要获取多个元素,则不能只传递索引列表。
例子:
a = [-2,1,5,3,8,5,6]
b = [1,2,5] # list of indexes
a[b] #this doesn't work
# expected output: [1,5,5]
为了解决这个问题,在链接的问题中提出了几个选项:
使用列表推导:
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [a[i] for i in b]
使用operator.itemgetter:
from operator import itemgetter
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print itemgetter(*b)(a)
或使用 numpy 数组(接受列表索引)
import numpy as np
a = np.array([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
print list(a[b])
我的问题是:为什么普通列表不接受这个?这不会与正常的索引 [start:end:step] 冲突,并且将提供另一种访问列表元素的方式,而无需使用外部库。
我的这个问题并不是为了吸引基于意见的答案,而是想知道 Python 中是否有这个功能不可用的具体原因,或者它是否会在未来实现。
【问题讨论】:
-
不太明白,你知道使用切片符号来操作列表吗? stackoverflow.com/questions/509211/…
-
@PyNico OP 在他的问题中提到了切片表示法,但他问的是如何获取单个切片无法表示的多个元素
-
噢,对不起,我当时不明白。我无法回答这个问题。
-
你的意思是你想得到
[-2,1,5,3,8,5,6][1,2,5] => [1, 5, 5]? -
[a[i] for i in b]有什么问题?对我来说似乎很简单。