简体   繁体   English

在python中检查条件后,从列表中替换元素:以“ pythonic方式”进行操作

[英]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.

相关问题 Pythonic方法检查条件是否适用于列表的任何元素 - Pythonic way of checking if a condition holds for any element of a list 如果满足条件,修改列表元素的Python方法 - Pythonic way to modify list element if condition is met 替换列表列表内容的pythonic方法? - pythonic way of replacing the content of list of list? 检查对象是否为列表的pythonic方法是什么? - What is the pythonic way of checking if an object is a list? Pythonic检查列表中是否有多个元素的方法 - Pythonic way of checking if several elements are in a list 从列表中弹出随机元素的最pythonic方法是什么? - What is the most pythonic way to pop a random element from a list? 确定列表中第一个真实条件的pythonic方法 - pythonic way to identify first true condition in a list Pythonic方式在列表推导中使用第二个条件 - Pythonic way to use the second condition in list comprehensions 在检查列值是否包含作为列表中元素的字符串后,如何将列表中的元素分配给数据框列? (Python) - How to assign element from a list to a dataframe column after checking if a column value contains a string that is an element in the list? (Python) 以功能方式用Python替换List中满足特殊条件的元素 - Replacing the elements that meet special condition in List with Python in a functional way
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM