[英]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. 我想通过从大于10的任何元素中减去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. 但这不是“ pythonic”编码方式。 I would be fine with this loop if I was using Fortran but Python is better than these structured loops.
如果我使用的是Fortran,那么使用此循环就可以了,但是Python比这些结构化循环要好。
Can I do this in another way? 我可以用其他方式吗?
A very pythonic way is to use a list comprehension with a conditional expression : 一种非常Python化的方法是将列表理解与条件表达式一起使用 :
>>> a = [2,4,5,12]
>>> a = [x-10 if x > 10 else x for x in a]
>>> a
[2, 4, 5, 2]
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.