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.
You’re nearly there, except that the
ifcomes at the end: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.