dobbs dobbs - 2 months ago 6
Python Question

Update list in-place, converting 'True'/'False' elements to 1/0

In python, supposed I have a list:

l = [ 'True', 'False', 'myname', 1, 0, 'foo' ]


and I want to convert the strings
'True'
or
'False'
to
1
or
0
, what is the best way to do this and still retain the index that the value had originally? i.e. the output would look like:

l = [ 1, 0, 'myname', 1, 0, 'foo' ]

Answer

List comprehension is your friend:

>>> l = [ 'True', 'False', 'myname', 1, 0, 'foo'] 
>>> mapping = {"True": 1, "False": 0}
>>> [mapping.get(x, x) for x in l]