In-place value conversion in Python
Tired of long ternary operators?
v = 'yes' if x == 1 else 'no' if x == 0 else 'maybe'
Use a dict for in-place conversion!
v = {1: 'yes', 0: 'no', None: 'maybe!'}[x]
Written by Eugene Pankov
Related protips
2 Responses
v = (x == 1) and 'yes' or (x == 0) and 'no' or 'maybe'
over 1 year ago
·
But behavior will be a bit different. None in dict won't catch values other than 1 or 0. :(
Anyway good sample. Thanks.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#