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.
解决方案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.