简体   繁体   中英

Replacing the elements that meet special condition in List with Python in a functional way

I have a list [1, 2, 3, -100, 2, -100] . I need to replace -100 with "ERROR" , and others to their corresponding string.

I could code like this.

resList = []
for val in list:
    if val == -100:
        resList.append("ERROR")
    else:
        resList.append("%d" % val)

How can I do the same thing in a functional way.

I tried mapping.

resList = map(lambda w: if w == -100: "ERROR" else:("%d" % val), list)

However it doesn't compile as it has syntax error. What's wrong with them?

This one doesn't work:

resList = map(lambda w: if w == -100: "ERROR" else:("%d" % val), list)

It fails because you can't have a block inside a lambda expression.

I prefer the list comprehension approach:

resList = ['ERROR' if item == -100 else item for item in yourlist]

This shouldn't generate any errors. If you are getting errors, it's because there are errors elsewhere in your program. Or perhaps the indentation is wrong. Post the specific error message you get.

Also, I'd advise you not to use the name list for local variables because it hides the builtin with the same name.

这有效:

["ERROR" if -100 == val else str(val) for val in list]

如果您正确使用python三元运算符并且始终使用“ w” lambda参数,则该映射将起作用。

map(lambda w: "ERROR" if w == -100 else ("%d" % w), list)

This code will do this:

list = [1, 2, 3, -100, 2, -100]
resList = ['ERROR' if x == -100 else str(x) for x in list ]

This is some weird looking code, but it works:

resList = ["%s%s" % ("ERROR" * (val == -100), ("%d" % val) * (val != -100)) for val in list]

produces:

['1', '2', '3', 'ERROR', '2', 'ERROR']

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.

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