Sum elements in list under condition(python)

sum( int(i.replace(',',''))if re.search('\d',i)!=None for i in list)

I would like to sum all elements in a list. The problems is that elements are strings, some of them have numbers in them and i would like convert them into integers and then added them up. That is why I need to check if there are numbers in the string. How can I add a condition to the list in the sum function. Also I want to use the sum function I dont want to just iterate through the list and then add to a variable.

Answers


How can I add a condition to the list in the sum function.

You're nearly there, except that the if comes at the end:

sum(int(i.replace(',','')) for i in list if re.search(r'\d', i))

Having said this, the overall approach is not bullet-proof. It would choke on inputs that mix digits with other characters (e.g. 'a1').

Also, the use of the comma as the thousands separator is not universal. Some locales use it to mark the radix point. In those locales, your code would produce incorrect values for numbers with commas in them.


Need Your Help

WinJS, return a promise from a function which may or may not be async

javascript asynchronous winjs promise

I have a situation where my WinJS app wants to call a function which may or may not be async (e.g. in one situation I need to load some data from a file (async) but at other times I can load from a...

How to use 2 tiling background images using the HTML tag and the BODY tag

html css

I have a tiling background image, but I want to overlay another tiling image over it. I have tried using: