简体   繁体   中英

Replacing an element from list after checking for condition in python: doing it the “pythonic way”

I have a list of numbers such as:

a = [2,4,5,12]

I want to change the list by subtracting 10 from any element that is greater than 10.

I can do the following for that:

i = 0
for ax in a:
    if ax>10:
       ax = ax-10
       a[i] = ax
    i = i+1

But this is not a "pythonic" way of coding. I would be fine with this loop if I was using Fortran but Python is better than these structured loops.

Can I do this in another way?

A very pythonic way is to use a list comprehension with a conditional expression :

>>> a = [2,4,5,12]
>>> a = [x-10 if x > 10 else x for x in a]
>>> a
[2, 4, 5, 2]
>>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM