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
a = [b + 4 if b < 0 else b for b in a]
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] :
enumerate
a[i]
for i, x in enumerate(a): if x < 0: a[i] = x + 4
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
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:
map
b = map(lambda x: x + 4 if x < 0 else x, a)
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]]
Source: https://habr.com/ru/post/903927/More articles:Response.StatusDescription not sent from JsonResult to jQuery - jsonDevise - Recoverable (Password Reset) - passwordsScalatest BDD: Spec vs. WordSpec vs. FlatSpec, which should I use? - scalaCorrect appDelegate method to run Flurry? - iosScrapy monitors and cleans unresolved links - pythonPHP string in hex - phphttps://translate.googleusercontent.com/translate_c?depth=1&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/903929/libraries-to-verify-file-format-by-header&usg=ALkJrhjKgeKqu8X57UmXWSjlpARnAvjHuwhttps://translate.googleusercontent.com/translate_c?depth=1&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/903930/what-needs-to-be-on-main-thread&usg=ALkJrhibCQz4TOKx_aPHHXFNStwmYIh25QAdd integer column to existing mysql table based on existing column - mysqlExcel: computing only a column - excelAll Articles