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

后端 未结 8 1204
醉梦人生
醉梦人生 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条回答
  •  -上瘾入骨i
    2020-12-08 10:47

    Yet another alternative for better performance if that is important to you- it is by no means the most Pythonic but I am pretty sure it is the most efficient:

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

    Note: You do not need to convert to a list in Python 2. However you do in Python 3 onwards (if any future visitors may have a similar issue).

提交回复
热议问题