Home > Mobile >  Change the values in the nested list according to the specified index list
Change the values in the nested list according to the specified index list

Time:01-07

How to change the values in nested list

How to change the values in the list base on the indexes To clarify, I originally have the_list

the_list = [['a','a','a'],['b','b','b'],['b','b','b'],['c','c','c']]

However, I would like to change the values in the_list above that have the index/position in the indexA

indexA = [(0,2),(1,2),(0,1)]   

which I would like to change the following index of the_list to 'hi'

the_list[0][2]      
the_list[1][2] 
the_list[0][1]  

Therefore, the expected output is

the_list = [['a', 'hi', 'hi'], ['b', 'b', 'hi'], ['b', 'b', 'b'],['c', 'c', 'c']]  

Currently I'm doing it manually by what follows:

the_list = [['a','a','a'],['b','b','b'],['b','b','b'],['c','c','c']]     
the_list[0][2] = 'hi'     
the_list[1][2] = 'hi'      
the_list[0][1] = 'hi'     

Output:

the_list = [['a', 'hi', 'hi'], ['b', 'b', 'hi'], ['b', 'b', 'b'],['c', 'c', 'c']]

Please kindly recommend the better way of doing it

Thank you in advance

CodePudding user response:

for i, j in indexA:
    the_list[i][j] = 'hi'

print(the_list)

gives

[['a', 'hi', 'hi'], ['b', 'b', 'hi'], ['b', 'b', 'b'], ['c', 'c', 'c']]

CodePudding user response:

you can try a parallel looping through your Index list to change the main list

for x,y in IndexA:
    the_list[x][y] = "Hi"

CodePudding user response:

The only way to change the value in the list is to change it manually as you did. The only thing you can do is use a For Loop instead of writing manually like below.

change_to = 'hi'
indexA = [(0,2),(1,2),(0,1)]   
for i in indexA:
  the_list[i[0]i[1]] = change_to

You have to manually refer to change the value. So improve it this way.

hope it helps

  • Related