Reputation: 1039
I would like to replace None
value with 0
or 1
depending on some external condition. My solution is:
my_list = [3, 4, 5, None, 6, 7, None, 8, None]
my_list = [(1 if external_string == "ONE" else 0) if v is None else v for v in my_list]
Is this a pythonic way to solve the problem? Let's suppose to have more than two possible value of string in order to assign, for example, 0 if external_string
is "ZERO"
, 1 if external_string
if "ONE"
, 2 if external_string
is "TWO"
and so on: in this case the way I write the code above is stylistically acceptable?
Upvotes: 0
Views: 539
Reputation: 1121904
Since external_string
doesn't change in the loop, so you can calculate the replacement value once:
replacement = 1 if external_string == 'ONE' else 0
my_list = [replacement if v is None else v for v in my_list]
If the external_string
test uses data that changes or is more complex, just create a function:
def replace(value):
if value is not None:
return value
return 1 if external_string == 'ONE' else 0
my_list = [replace(v) for v in my_list]
Don't try to cram everything into a list comprehension; readability counts!
For multiple options, consider using a dictionary mapping the external string to replacement values:
external_string_map = {'ONE': 1, 'TWO': 2} # etc.
replacement = external_string_map.get(external_string, 0)
my_list = [replacement if v is None else v for v in my_list]
Upvotes: 5
Reputation: 107287
If there are a lot of options for external_string
you better to use a dictionary that keeps all the possibilities then choose the proper replacing value using external_string
:
all_options = {'ZERO':0, 'ONE':1, 'TWO':2, 'THREE': 3}
my_list = [all_options[external_string] if v is None else v for v in my_list]
Note that instead of using a direct indexing you can also use dict.get()
method which will return None (by default) if the key doesn't exist in the dictionary or you can pass a custom value in order to be passed in case of lacking the key.
Upvotes: 5