条件下列表中的元素求和(python) [英] Sum elements in list under condition(python)

查看:497
本文介绍了条件下列表中的元素求和(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想对列表中的所有元素求和.问题在于元素是字符串,其中一些元素包含数字,我想将它们转换为整数,然后将它们加起来.这就是为什么我需要检查字符串中是否有数字的原因.如何在sum函数中向列表添加条件.我也想使用求和函数,我不想只遍历列表,然后将其添加到变量中.

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.

推荐答案

如何在sum函数中将条件添加到列表中.

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

您快到了,除了if位于末尾:

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.

这篇关于条件下列表中的元素求和(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆