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:
i开发者_开发问答f 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.
this works:
["ERROR" if -100 == val else str(val) for val in list]
The map will work if you use the python ternary operator correctly and the "w" lambda parameter consistently.
map(lambda w: "ERROR" if w == -100 else ("%d" % w), 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']
This code will do this:
list = [1, 2, 3, -100, 2, -100]
resList = ['ERROR' if x == -100 else str(x) for x in list ]
精彩评论