Kartik Aggarwal
Kartik Aggarwal

Reputation: 1

How to replace original values in list according to the indexed values of the original values

I have these indexed values like these:

{0:0, 22:1 , 334: 2 , 6666:3}

And have a 2D list:

[[0,22],[22,334,6666],[22,334],[0,6666]]

I am expecting something like this:

[[0,1],[1,2,3],[1,2],[0,3]]

Upvotes: 0

Views: 22

Answers (1)

Adam Smith
Adam Smith

Reputation: 54213

Sure! Try something like:

indexes = {0: 0, 22: 1, 334: 2, 6666: 3}

src = [[0,22],[22,334,6666],[22,334],[0,6666]]
result = [[indexes.get(key) for key in sublst] for sublst in src]

Unwrapping the list comprehension you've got something like:

result = []
for sublst in src:
    result_sublst = []
    for key in sublst:
        if key in indexes:
            value = indexes[key]
            result_sublst.append(value)
        else:
            # if your list contains a value that isn't in the
            # indexes table
            result_sublst.append(None)
    result.append(result_sublst)

Upvotes: 1

Related Questions