0

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)]

2 Answers 2

1

A little bit of readability. The nested list comp is excessive IMO. array2 is really the wrong data structure for what it is doing, so my first inclination is to make it a dictionary/mapping, as that is how you are using it here.

array1 = [[1,2,3],[4,5,6],[7,8,9]]
array2 = [['a','b','c'],[7,4,1]]

conversion = {}
letter_list, num_list = array2
for num, letter in zip(num_list, letter_list):
    conversion[num] = letter

output = [
    [conversion.get(num, num) for num in num_list] for num_list in array1 
]

# [['c', 2, 3], ['b', 5, 6], ['a', 8, 9]]
Sign up to request clarification or add additional context in comments.

1 Comment

I agree this is much better than a one-liner. Well done!
0

This should get what you want in one line:

[[[x]+z[1:] for z in array1 if z[0] == y][0] for x, y in zip(*array2)]
[['a', 8, 9], ['b', 5, 6], ['c', 2, 3]]

for loop version:

output = []
for i, x in enumerate(array2[0]):
    for y in array1:
        if y[0] == array2[1][i]:
            output.append([x]+y[1:])
output

6 Comments

Yeah the one-liner is like totally unmaintainable - an incomprehensible comprehension.
Op wanted the list comprehension version...@barny
Some people want to e.g. juggle knives, doesn’t make it a good idea. (Wasn’t my downvote, BTW)
@barny I agree with you. I know the pain to maintain "fancy" codes
I like your method. I agree, the loop version might be best. I recommend swapping the order of the loops so the order of output matches array1
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.