-3

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?

Georgy
  • 12,464
  • 7
  • 65
  • 73
Geo
  • 9
  • 5
  • its a method for caesar cypher. i cant do that. every list its one separate part of the decryption – Geo Dec 10 '20 at 17:43
  • 3
    @Geo If it's a caesar cypher there's a much better method of doing this. You just need to apply the letter offsets and mod 26. – ssp Dec 10 '20 at 17:47
  • @Moosefeather i searched the net, and i told that same thing to my professor. but he insisted in this method. perhaps for teaching purposes. but i agree, its not the best intuitive method, even for teaching a beginner like me – Geo Dec 10 '20 at 17:51
  • See [zip](https://docs.python.org/3/library/functions.html#zip). – Mark Tolonen Dec 10 '20 at 17:57
  • Same question but for NumPy: [NumPy selecting specific column index per row by using a list of indexes](https://stackoverflow.com/q/23435782/7851470) – Georgy Dec 10 '20 at 18:26

1 Answers1

2

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)]
Georgy
  • 12,464
  • 7
  • 65
  • 73
ssp
  • 1,666
  • 11
  • 15