modify list element with list comprehension in python

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

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

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

提交回复
热议问题