modify list element with list comprehension in python

前端 未结 5 2177
你的背包
你的背包 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:05

    This version is older, it would 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 conditional expressions as in Adam Wagner or BenH answers

提交回复
热议问题