Tanner
Tanner

Reputation: 5

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

Upvotes: 0

Views: 66

Answers (2)

yatu
yatu

Reputation: 88275

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]]

Upvotes: 1

Akaisteph7
Akaisteph7

Reputation: 6505

To keep in line with your code, I would just change it to this:

l = ['FooA','FooB','FooC','FooD']
data = [['FooB','FooD'],['FooD','FooC']]
indices = []

for sublist in data:
    temp = []
    for x in sublist:
        temp.append(l.index(x))
    indices.append(temp)

print(indices)
# [[1, 3], [3, 2]]

Upvotes: 0

Related Questions