简体   繁体   中英

Pythonic way to creating a list of certain elements

Taking a list, l , I would like to generate a new list of the elements at indexes:

0, 1, 2, 3, 2, 4, 5, 4, 6, 7, 6, 8, 9, 8, 0

I know it seems a bit strange, but it is necessary for a problem .


As for what I have tried, I am currently using the following, but was hoping that someone has something shorter and cleaner than this.

[*l[0:3], l[3], l[2], l[4], l[5], l[4], l[6], l7], l[6], l[8], l[9], l[8], l[0]]

You can use a list comprehension:

source = [......]
indexes = [.......]
filteredByIndexes = [source[i] for i in indexes]

Using map with an item getter should do the job:

>>> letters = list('ABCDEFGHIJ')
>>> indexes = [0, 1, 2, 3, 2, 4, 5, 4, 6, 7, 6, 8, 9, 8, 0]
>>> print(list(map(letters.__getitem__, indexes)))
['A', 'B', 'C', 'D', 'C', 'E', 'F', 'E', 'G', 'H', 'G', 'I', 'J', 'I', 'A']
>>> 

Items used as l values are equal to their index, so that you can verify result easily:

indexes = [0, 1, 2, 3, 2, 4, 5, 4, 6, 7, 6, 8, 9, 8, 0]

l = list(range(15))
print(l)  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

result = [l[i] for i in indexes]
print(result)  # [0, 1, 2, 3, 2, 4, 5, 4, 6, 7, 6, 8, 9, 8, 0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM