获取具有给定索引的Python列表的子列表?

时间:2014-03-14 18:00:44

标签: python list python-2.7

我有一个Python列表,比如a = [0,1,2,3,4,5,6]。我还有一个索引列表,比如b = [0,2,4,5]。如何获取a的元素列表,其中索引位于b

8 个答案:

答案 0 :(得分:30)

您可以使用 list comprehension 来获取该列表:

c = [a[index] for index in b]
print c

这相当于:

c= []
for index in b:
    c.append(a[index])
print c

<强>输出:

[0,2,4,5]

注意:

请记住,some_list[index]是用于访问特定索引中list元素的符号。

答案 1 :(得分:20)

有些不同......

>>> a = range(7)
>>> b = [0,2,4,5]
>>> import operator
>>> operator.itemgetter(*b)(a)
(0, 2, 4, 5)

itemgetter函数将一个或多个键作为参数,并返回一个函数,该函数将返回参数中给定键处的项。所以在上面,我们创建了一个函数,它将返回索引0,索引2,索引4和索引5处的项,然后将该函数应用于a

它似乎比同等列表理解

快得多
In [1]: import operator

In [2]: a = range(7)

In [3]: b = [0,2,4,5]

In [4]: %timeit operator.itemgetter(*b)(a)
1000000 loops, best of 3: 388 ns per loop

In [5]: %timeit [ a[i] for i in b ]
1000000 loops, best of 3: 415 ns per loop

In [6]: f = operator.itemgetter(*b)

In [7]: %timeit f(a)
10000000 loops, best of 3: 183 ns per loop

至于为什么itemgetter更快,理解必须执行额外的Python字节码。

In [3]: def f(a,b): return [a[i] for i in b]

In [4]: def g(a,b): return operator.itemgetter(*b)(a)

In [5]: dis.dis(f)
  1           0 BUILD_LIST               0
              3 LOAD_FAST                1 (b)
              6 GET_ITER
        >>    7 FOR_ITER                16 (to 26)
             10 STORE_FAST               2 (i)
             13 LOAD_FAST                0 (a)
             16 LOAD_FAST                2 (i)
             19 BINARY_SUBSCR
             20 LIST_APPEND              2
             23 JUMP_ABSOLUTE            7
        >>   26 RETURN_VALUE

虽然itemgetter是在C:

中实施的单个调用
In [6]: dis.dis(g)
  1           0 LOAD_GLOBAL              0 (operator)
              3 LOAD_ATTR                1 (itemgetter)
              6 LOAD_FAST                1 (b)
              9 CALL_FUNCTION_VAR        0
             12 LOAD_FAST                0 (a)
             15 CALL_FUNCTION            1
             18 RETURN_VALUE

答案 2 :(得分:7)

如果您是functional programming的粉丝,可以使用maplist.__getitem__

>>> a = [0,1,2,3,4,5,6]
>>> b = [0,2,4,5]
>>> map(a.__getitem__, b)
[0, 2, 4, 5]
>>>

列表理解方法虽然在Python中更为规范......

答案 3 :(得分:3)

如果KeyError包含b中不存在的索引,则许多提议的解决方案将生成a。如果需要,以下内容将跳过无效索引。

>>> b = [0,2,4,5]
>>> a = [0,1,2,3,4,5,6]
>>> [x for i,x in enumerate(a) if i in b]
[0, 2, 4, 5]
>>> b = [0,2,4,500]
>>> [x for i,x in enumerate(a) if i in b]
[0, 2, 4]

enumerate生成索引,值对的元组。由于我们同时拥有项目及其索引,因此我们可以检查b

中是否存在索引

答案 4 :(得分:3)

所有提及的方法和Python dictionary: Get list of values for list of keys中的其他方法的速度比较:

Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Jan 19 2016, 12:08:31) [MSC v.1500 64 bit (AMD64)] on win32

In[2]: import numpy.random as nprnd
idx = nprnd.randint(1000, size=10000)
l = nprnd.rand(1000).tolist()
from operator import itemgetter
import operator
f = operator.itemgetter(*idx)
%timeit f(l)
%timeit list(itemgetter(*idx)(l))
%timeit [l[_] for _ in idx]  # list comprehension
%timeit map(l.__getitem__, idx)
%timeit list(l[_] for _ in idx)  # a generator expression passed to a list constructor.
%timeit map(lambda _: l[_], idx)  # using 'map'
%timeit [x for i, x in enumerate(l) if i in idx]
%timeit filter(lambda x: l.index(x) in idx, l)  # UPDATE @Kundor: work only for list with unique elements
10000 loops, best of 3: 175 µs per loop
1000 loops, best of 3: 707 µs per loop
1000 loops, best of 3: 978 µs per loop
1000 loops, best of 3: 1.03 ms per loop
1000 loops, best of 3: 1.18 ms per loop
1000 loops, best of 3: 1.86 ms per loop
100 loops, best of 3: 12.3 ms per loop
10 loops, best of 3: 21.2 ms per loop

所以最快的是f = operator.itemgetter(*idx); f(l)

答案 5 :(得分:2)

使用List Comprehension,这应该有用 -

li = [a[i] for i in b]

测试这个 -

>>> a = [0,10,20,30,40,50,60]
>>> b = [0,2,4,5]
>>> li = [a[i] for i in b]
>>> li
[0, 20, 40, 50]

答案 6 :(得分:1)

如果对你来说这对你来说很重要,那么还有另一种更好的表现方式 - 它绝不是最恐怖的,但我相信它是最有效的:

>>> list(filter(lambda x: a.index(x) in b, a))
[0, 2, 4, 5]

注意:您无需在Python 2中转换为list。但是,您可以在Python 3之后(如果将来有任何访问者遇到类似问题)。

答案 7 :(得分:1)

使用numpy.asarray。 Numpy允许通过索引列表获得数组的子数组。

>>> import numpy as np
>>> a = [0,10,20,30,40,50,60]
>>> b = [0,2,4,5]
>>> res = np.asarray(a)[b].tolist()
>>> res
[0, 20, 40, 50]