I'm doing something like this to sum up all values from start to end.
big_list = line.split(delim)
sum( [int(float(item)) for item in big_list[start:end]] )
Sometimes an element of big_list may be empty, in which case the conversion fails. Can I make it work with empty strings in an elegant way, without changing too much above?
Assuming that empty elements should be zero:
sum(int(float(item)) for item in big_list[start:end] if item)
# ^ skip over ""
Note that:
sum can take the generator expression as an argument, there's no need to build the list; and"" evaluates False-y, so this is equivalent to if item != "".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