Python: comparing lists

I ran into a little problem. Let's say I have two lists:

list_A = ['0','1','2'] list_B = ['2','0','1'] 

Then I have a list of lists:

 matrix = [ ['56','23','4'], ['45','5','67'], ['1','52','22'] ] 

Then I need to iterate through list_A and list_B and use them effectively as codes. For example, I take the first number from the list of A and B, which will be "0" and "2", then I use them as coordinates: print matrix[0][2]

Then I need to do the same for the second number in lists A and B and the third number in lists A and B, etc., as if long lists A and B were not. How to do it in a loop?

+6
python list
source share
3 answers
 matrix = [ ['56','23','4'], ['45','5','67'], ['1','52','22'] ] list_A = ['0','1','2'] list_B = ['2','0','1'] for x in zip(list_A,list_B): a,b=map(int,x) print(matrix[a][b]) # 4 # 45 # 52 
+8
source share
 [matrix[int(a)][int(b)] for (a,b) in zip(list_A, list_B)] 
+2
source share

The zip function can be used here. It will generate a list of pairs from list_A and list_B.

 for (x,y) in zip(list_A, list_B): # do something with the coordinates 
0
source share

All Articles