简体   繁体   English

python列表理解的语法错误

[英]Syntax error with python list comprehension

I have a python list of integers with 0 and 1 , now I want to change 0 to -1 , so I'm doing this:我有一个包含01的python 整数列表,现在我想将0更改为-1 ,所以我这样做:

[v[i] = -1 for i in range(len(v)) if v[i] == 0]

then I get syntax error .然后我得到syntax error what's wrong with this?这有什么问题?

I also tried the map + lambda but still not working.我也试过 map + lambda 但还是不行。

map(lambda x: -1 if x == 0 else x, v)

this time it's not syntax error but just didn't change anything to v. what's wrong with this and what's the right solution?这次不是语法错误,只是没有将任何内容更改为 v。这有什么问题,正确的解决方案是什么?

v[i] = -1 is not an expression (assignments are not expressions in Python), it's a statement, therefore it cannot be used in a generator expression like (expr) for item in iterable . v[i] = -1不是表达式(赋值不是 Python 中的表达式),它是一个语句,因此它不能用在生成器表达式中,例如(expr) for item in iterable

Use a normal for loop:使用普通的for循环:

for i in range(len(v)):
    if v[i] == 0:
        v[i] = -1

你可以用这个

v = [-1 if x == 0 else x for x in v]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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