Change list combo element in python

people,

I want to change a list item with a list. For example, if the item is negative, add 4 to it.

So the list

a = [1, -2 , 2] 

will be converted to

 a = [1, 2, 2] 

The following code works, but I wonder if there is a better way to do this?

Thanks.

 for i in range(len(a)): if a[i]<0: a[i] += 4 
+6
source share
5 answers
 a = [b + 4 if b < 0 else b for b in a] 
+11
source

If you want to change the list in place, this is the best way. List Accounting will create a new list. You can also use enumerate , and the assignment must be done with a[i] :

 for i, x in enumerate(a): if x < 0: a[i] = x + 4 
+6
source

This version is older, it will work on Python 2.4

 >>> [x < 0 and x + 4 or x for x in [1, -2, 2]] 0: [1, 2, 2] 

For newer versions of Python, use as in Adam Wagner, or in BenH's response

+3
source

Try the following:

  b = [x + 4 if x < 0 else x for x in a] 

Or, if you like map more than a list comprehension:

  b = map(lambda x: x + 4 if x < 0 else x, a) 
+2
source

Why mutate when you can just return a new list that looks the way you want?

 [4 + x if x < 0 else x for x in [1, -2, 2]] 
+1
source

Source: https://habr.com/ru/post/903927/


All Articles