I have a long list of strings in the following format:
[...
(0.5, 'house', 'flower'),
(0.213, 'garden', 'flowerpot'),
(None, 'mulch', 'hunting'),
(0.9, 'flower', 'tulip'),
(0.34, 'party', 'music'),
(None, 'piano', 'trowel'),
(0.138, 'fertilizer', 'cow')
...]
And before I can sort the list based on the first element, I have to convert the None types to floats. How do I change all the Nones in the list to float 0?
I am trying:
mylist = map(lambda x: 0 if x[0] == None, else x, mylist)
But somewhere I am going wrong with the syntax - anyone have advice for a Pythonic replace all on Nones in the first element of each string for the whole list?
You can use:
list(map(lambda x: (0.0,)+x[1:] if x[0] is None else x,mylist))
which produces:
>>> list(map(lambda x: (0.0,)+x[1:] if x[0] is None else x,mylist))
[(0.5, 'house', 'flower'), (0.213, 'garden', 'flowerpot'), (0.0, 'mulch', 'hunting'), (0.9, 'flower', 'tulip'), (0.34, 'party', 'music'), (0.0, 'piano', 'trowel'), (0.138, 'fertilizer', 'cow')]
The code works as follows: we thus perform a mapping with lambda x: (0.0,)+x[1:] if x[0] is None else x
as mapping function.
This is a ternary operator: if the first element x[0] is None
, we return (0.0,)+x[1:]
so we construct a new tuple with 0.0
as first element, and x[1:]
as remaining elements. If the first element is not None
, we simply return x
.
This will work for every tuple, given it has at least one element. If there can be empty tuples in the list, we can alter the expression to:
list(map(lambda x: (0.0,)+x[1:] if x and x[0] is None else x,mylist))