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

后端 未结 8 1203
醉梦人生
醉梦人生 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:43

    You can use list comprehension to get that list:

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

    This is equivalent to:

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

    Output:

    [0,2,4,5]
    

    Note:

    Remember that some_list[index] is the notation used to access to an element of a list in a specific index.

    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题