Getting a sublist of a Python list, with the given indices?

后端 未结 8 1207
醉梦人生
醉梦人生 2020-12-08 09:50

I have a Python list, say a = [0,1,2,3,4,5,6]. I also have a list of indices, say b = [0,2,4,5]. How can I get the list of elements of a

8条回答
  •  遥遥无期
    2020-12-08 10:21

    A bit of speed comparison for all mentioned methods and others from 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
    

    So the fastest is f = operator.itemgetter(*idx); f(l)

提交回复
热议问题