Search code examples
pythonlistindexingsublist

Indexing a list of lists using a list of the same strings


I am attempting to create a list of lists replacing a given string with the indices of the string from another list.

I have tried some for loops as shown below

l = ['FooA','FooB','FooC','FooD']
data = [['FooB','FooD'],['FooD','FooC']]
indices = []
for sublist in data:
    for x in sublist:
        indecies.append(l[list.index(x)])

I am hoping to get: indices = [[1,3],[3,2]] although the data types of the elements can be str if needed

the closest I could get to getting something like this was a 2x2 list of lists populated by 2's


Solution

  • The way I would do this is by first creating a dictionary mapping strings to their respective indices, and use a nested list comprehension to look up the values from the nested list:

    from itertools import chain
    
    d = {j:i for i,j in enumerate(chain.from_iterable(l))}
    # {'FooA': 0, 'FooB': 1, 'FooC': 2, 'FooD': 3}
    [[d[j] for j in i] for i in data]
    # [[1, 3], [3, 2]]