modify list element with list comprehension in python

前端 未结 5 2334
你的背包
你的背包 2021-02-20 17:41

folks,

I want to modify list element with list comprehension. For example, if the element is negative, add 4 to it.

Thus the list

a = [1, -2 ,          


        
5条回答
  •  隐瞒了意图╮
    2021-02-20 18:19

    Try this:

     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)
    

提交回复
热议问题