Shaykh_Python
Shaykh_Python

Reputation: 49

Substituting the values from list of lists by the values of another list based on indices in python

Given lists are as follows:

mainList = [[0, 2, 1, 4, 3],
       [0, 2, 1, 3, 4],
       [1, 0, 2, 3, 4],
       [2, 1, 0, 3, 4],
       [1, 0, 2, 3, 4],
       [0, 1, 2 ,3, 4],
       [0, 2, 1, 3, 4]]

and list_indices = [0, 1, 2, 3, 4], list_value = [0.0, 0.2, 0.4, 0.4, 0.9].

The required list of lists is as follows:

mainList_mapped = [[0.0, 0.4, 0.2, 0.9, 0.4],
               [0.0, 0.4, 0.2, 0.4, 0.9],
               [0.2, 0.0, 0.4, 0.4, 0.9],
               [0.4, 0.2, 0.0, 0.4, 0.9],
               [0.2, 0.0, 0.4, 0.4, 0.9],
               [0.0, 0.2, 0.4, 0.4, 0.9],
               [0.0, 0.4, 0.2, 0.4, 0.9]]

Values of the mainList will be considered as indices and be replaced by the corresponding indices values in list_value. I tried but the code didn't work.

mainList_mapped = []

for ls in mainList:
    for (i, j) in zip(ls, list_value):
        ls[i] = j
    
    mainList_mapped.append(ls)

A similar answer is here How to replace values at specific indexes of a python list? but I'm getting Error (TypeError: list indices must be integers or slices, not float) in getting my results. Any help will be appreciated.

Upvotes: 1

Views: 66

Answers (3)

U13-Forward
U13-Forward

Reputation: 71570

Try using a nested list comprehension:

print([[list_value[x] for x in i] for i in mainList])

Output:

[[0.0, 0.4, 0.2, 0.9, 0.4], [0.0, 0.4, 0.2, 0.4, 0.9], [0.2, 0.0, 0.4, 0.4, 0.9], [0.4, 0.2, 0.0, 0.4, 0.9], [0.2, 0.0, 0.4, 0.4, 0.9], [0.0, 0.2, 0.4, 0.4, 0.9], [0.0, 0.4, 0.2, 0.4, 0.9]]

Upvotes: 0

sunnytown
sunnytown

Reputation: 1996

You should be doing it like this:

mainList_mapped = []
for row in mainList:
    row_mapped = []
    for index in row:
        row_mapped.append(list_value[index])
    mainList_mapped.append(row_mapped)

Upvotes: 1

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

You can create a function that rearranges a list based on given indices:

def rearrange(value, indices):
    return [value[i] for i in indices]

Now apply this function to all the lists in the mainlist:

>>> result = [rearrange(list_value, indices) for indices in mainList]
>>> result
[[0.0, 0.4, 0.2, 0.9, 0.4],
 [0.0, 0.4, 0.2, 0.4, 0.9],
 [0.2, 0.0, 0.4, 0.4, 0.9],
 [0.4, 0.2, 0.0, 0.4, 0.9],
 [0.2, 0.0, 0.4, 0.4, 0.9],
 [0.0, 0.2, 0.4, 0.4, 0.9],
 [0.0, 0.4, 0.2, 0.4, 0.9]]

In this case it was easier because list_indices are sorted, but if it were shuffled, you could change the rearrange function like this:

mapping = dict(zip(list_indices, list_value))

def rearrange(mapping, indices):
    return [mapping[i] for i in indices]

Upvotes: 0

Related Questions