简体   繁体   中英

Extract elements from a list of lists based on a list of indices for each list

I want to extract from this nested list:

[['c', 'd', 'e', 'f', 'g'], 
 ['a', 'b', 'c', 'd', 'e'], 
 ['n', 'o', 'p', 'q', 'r'], 
 ['t', 'u', 'v', 'w', 'x']]

the items by the indices for each row:

[2, 1, 4, 0]

The expected output will be:

['e', 'b', 'r', 't']

How can I do it?

This works:

lst = [['c', 'd', 'e', 'f', 'g'], 
       ['a', 'b', 'c', 'd', 'e'], 
       ['n', 'o', 'p', 'q', 'r'], 
       ['t', 'u', 'v', 'w', 'x']]

indexes = [2, 1, 4, 0]
output = [sublst[index] for sublst, index in zip(lst, indexes)]

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