python元素求和,条件下列表中的元素求和(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.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值