Ad

Create List Of Strings From Nested List Of Indices And Nested List Of Strings

I have two nested lists: one that holds lists of indices, and the other with lists of strings. The 0th indices sublist corresponds to the 0th strings sublist. Inside of each indices sublist are the indices of the strings of the corresponding strings sublist that I want to pull into a new nested list.

nested_indices = [[3,4,5],[0,1,2],[6,7,8]]
strings_list = [['0a','0b','0c','0d','0e','0f','0g','0g','0h', '0i'],
           ['1a','1b','1c','1d','1e','1f','1g','1g','1h', '1i'],
           ['2a','2b','2c','2d','2e','2f','2g','2g','2h', '2i'],
           ['3a','3b','3c','3d','3e','3f','3g','3g','3h', '3i'],
           ['4a','4b','4c','4d','4e','4f','4g','4g','4h', '4i'],
           ['5a','5b','5c','5d','5e','5f','5g','5g','5h', '5i'],
           ['6a','6b','6c','6d','6e','6f','6g','6g','6h', '6i'],
           ['7a','7b','7c','7d','7e','7f','7g','7g','7h', '7i'],
           ['8a','8b','8c','8d','8e','8f','8g','8g','8h', '8i'],
           ['9a','9b','9c','9d','9e','9f','9g','9g','9h', '9i']]

The lists inside nested_indices will be variable length in use. But for this example, this is what I'm hoping to get:

expected=[['0d','0e','0f'],['1a','1b','1c'],['2g','2g','2h']]

This is my code so far, which is not only not giving me the correct values, but is also losing the nested list structure.

new_list = []

for sublist in nested_indices:
    for (item, index) in enumerate(sublist):
        new_list.append(strings_list[item][index])
        
print(new_list)

Which results in: ['0d', '1e', '2f', '0a', '1b', '2c', '0g', '1g', '2h']

Where am I going wrong?

Ad

Answer

Use:

  • zip to pair corresponding sublists in both nested lists
  • list comprehension to get the corresponding values from paired sublists

Code

new_list = [[vals[i] for i in idxs] for idxs, vals in zip(nested_indices, strings_list)]

Result

[['0d', '0e', '0f'], ['1a', '1b', '1c'], ['2g', '2g', '2h']]
Ad
source: stackoverflow.com
Ad