fortran
fortran

Reputation: 75

Converting string to float with error handling inside a list comprehension

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?

Upvotes: 3

Views: 1164

Answers (1)

cs95
cs95

Reputation: 402844

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]

Upvotes: 2

Related Questions