[英]modify list element with list comprehension in python
folks, 乡亲,
I want to modify list element with list comprehension. 我想用list comprehension修改list元素。 For example, if the element is negative, add 4 to it. 例如,如果元素为负数,则向其中添加4。
Thus the list 因此列表
a = [1, -2 , 2]
will be converted to 将被转换为
a = [1, 2, 2]
The following code works, but i am wondering if there is a better way to do it? 以下代码有效,但我想知道是否有更好的方法来做到这一点?
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 almost the best way. 如果您想要就地更改列表,这几乎是最好的方法。 List comprehension will create a new list. 列表理解将创建一个新列表。 You could also use enumerate
, and assignment must be done to a[i]
: 你也可以使用enumerate
,并且必须对a[i]
进行赋值:
for i, x in enumerate(a):
if x < 0:
a[i] = x + 4
This version is older, it would work on Python 2.4 这个版本较旧,可以在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 conditional expressions as in Adam Wagner or BenH answers 对于较新版本的Python,使用条件表达式,如Adam Wagner或BenH答案
Try this: 试试这个:
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)
为什么要改变,当你可以返回一个看起来像你想要的新列表?
[4 + x if x < 0 else x for x in [1, -2, 2]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.