Consider the following list of lists:
list1 = [['1.1','1.2'],['2.1', '2.2'],[''],...]
This list contains lists with empty strings. To convert all strings in this list of lists to floats one could use list comprehension, such as:
[[float(j) for j in i] for i in list1]
(thanks to).
But there is one problem with the lists containing empty strings - they cause an exception:
ValueError: could not convert string to float:
Is there a way to use this kind of list comprehension without using loops explicitly?
Use an if condition inside the inner list comprehension to ignore empty strings:
[[float(j) for j in i if i] for i in list1]
if i will test the "truthiness" of strings. This will only return False for empty strings, so they are ignored.
Or, if you want to be more robust about it, use a function to perform the conversion with exception handling:
def try_convert(val):
try:
return float(val)
except ValueError, TypeError:
pass
[[float(z) for z in (try_convert(j) for j in i) if z] for i in list1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With