I have a python list of integers with 0
and 1
, now I want to change 0
to -1
, so I'm doing this:
[v[i] = -1 for i in range(len(v)) if v[i] == 0]
then I get syntax error
. what's wrong with this?
I also tried the map + lambda but still not working.
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[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
.
Use a normal for
loop:
for i in range(len(v)):
if v[i] == 0:
v[i] = -1
你可以用这个
v = [-1 if x == 0 else x for x in v]
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.