I am struggling to figure out how to mix nested list comprehension with a replacing Here is an example of the nested for loops that I am trying to convert
array1 = [[1,2,3],[4,5,6],[7,8,9]]
array2 = [['a','b','c'],[7,4,1]]
for i in array1:
value=i[0]
for val2 in array2[1]:
if value==val2:
#convert i to array2[0][array2[1].index(val2)]
I've tried this but it just converts everything to ['a','b','c']
In [34]: [[x if x == y else array2[0] for y in array2[1]] for x in array1]
Out[34]:
[[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']],
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']],
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]]
The result I am expecting is
In[35]:array1
Out[35]:
[['c',2,3],['b',5,6],['a',8,9]]
If list comprehension isn't the best way solve, this, I would appreciate that answer also. I could do this, but I don't think it's the most efficient way.
for ii in range(len(array1))
value = array1[ii]
...
array1[ii] = array2[0][array2[1].index(val2)]