Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list comprehension mirroring values

I tried to figure out the following problem through list comprehension but I couldn't make it work. I will show you how I solved the problem using a loop and a list comprehension.

So, I have a list that can have 0 to 6 elements in a range(6) and when I apply my function on it I want to change the values, as shown here:

l = [0, 1, 2, 3, 4, 5]
mirror = [5, 4, 3, 2, 1, 0]

I don't want to just rotate the array by 180 degrees but I actually want to replace the values. For example, my list looks like this now:

l = [2, 5]

Then l_inverted list should look like this:

l_inverted = [3, 0]

I came up with a regular way to solve it but ever since I started learning Python I've preferred list comprehensions.

l = [0, 3, 5]
mirror = [5, 4, 3, 2, 1, 0]
i = 0
for element in l:
    l[i] = mirror[element]
    i += 1

This actually inverts the l list. Here's my approach using a list comprehension:

l = [3, 5]
mirror = [5, 4, 3, 2, 1, 0]
for element in l:
    print(element)
    l = [mirror[element] if x==element else x for x in l]

This works fine. Until:

l = [0, 3, 5]
mirror = [5, 4, 3, 2, 1, 0]
for element in l:
    print(element)
    l = [mirror[element] if x==element else x for x in l]

So it will replace 5 with 0, 2 with 3 and both 5s (the new one too) become 0. Obviously, I don't want it like that.

Should I stick to the working solution or is there a smooth way to solve it with list comprehensions? I'm trying to practice list comprehensions at all times but it's not fully in my brain yet. Thanks a lot.

like image 670
Marcel Braasch Avatar asked May 20 '26 07:05

Marcel Braasch


2 Answers

If you want it as a list comprehension:

>> l = [0, 3, 5]
>> mirror = [5, 4, 3, 2, 1, 0]
>> l_inverted = [mirror[x] for x in l]
>> l_inverted
[5, 2, 0]
like image 140
DBedrenko Avatar answered May 21 '26 20:05

DBedrenko


You are drowning in a spoonful of water and trying to take us with you. You are using bad naming conventions that make your simple problem complicated to comprehend.

orig = [0, 1, 2, 3, 4, 5]
orig_rev = l[::-1]

selector = [0, 3, 5]

result = [orig_rev[i] for i in selector]
print(result )  # [5, 2, 0]
like image 35
Ma0 Avatar answered May 21 '26 20:05

Ma0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!