简体   繁体   中英

Reverse list item values

I want to reverse all the values in my list. My list is composed of 0, 1, 2 and 3 (for example [0,2,2,3,1,3,2]) and I want to reverse the values of the items (change all the 0 to 3, all the 1 to, all the 2 to 1 and all the 3 to 0 => [3,1,1,0,2,0,1]).

Is it possible in python ?

I tried to use list comprehensions without any success.

li=[0,2,2,3,1,3,2]
print(list(reversed(li)))

What I have: [0,2,2,3,1,3,2] What I want: [3,1,1,0,2,0,1]

Use a map and subtract each value with the maximum value in the list l :

>>> l = [0,2,2,3,1,3,2]
>>> list(map(max(l).__sub__, l))
[3, 1, 1, 0, 2, 0, 1]
>>> 

Or use a list comprehension:

>>> [max(l) - i for i in l]
[3, 1, 1, 0, 2, 0, 1]
>>> 

The reversed function will reverse the order of the list rather than the values in the list itself. There are a few ways you could do what you're trying to do using map to apply a function to every element of the list. Here is one that would work for your specific example:

list(map(lambda x: abs(x-3), li)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM