简体   繁体   English

字典中列表的字符串值总和

[英]Sum of string values of a list in dictionary

I am having trouble deriving the overall sum of string values. 我在导出字符串值的总和时遇到麻烦。 While I am able to generate the following if there are in integers form: 如果有整数形式,我可以生成以下内容:

size = {
    'serverA' : [10, 10],
    'serverB' : [3, 3, 3],
}

If I used sums = {k: sum(i for i in v if isinstance(i, int)) for k, v in size.items()} , I will be able to get output such as {'serverA': 20, 'serverB': 9} 如果我使用sums = {k: sum(i for i in v if isinstance(i, int)) for k, v in size.items()} ,我将能够获得诸如{'serverA': 20, 'serverB': 9}

However, instead of having integers in the values of the list, I got string as follows: 但是,我没有在列表的值中包含整数,而是得到如下字符串:

size = {
    'serverA' : ['10', '10'],
    'serverB' : ['3', '3', '3'],
}

And if I used the same command to generate the sum of values, while there are no errors, the sums are clearly wrong in which the output is {'serverA': 0, 'serverB': 0} 如果我使用同一命令生成值的总和,而没有错误,则总和显然是错误的,其中输出为{'serverA': 0, 'serverB': 0}

You can use map() to map the values to int s: 您可以使用map()将值映射到int

>>> {k: sum(map(int, v)) for k, v in size.items()}
{'serverA': 20, 'serverB': 9}

Note: if you have values that aren't integers this will raise a ValueError exception. 注意:如果您的值不是整数,则将引发ValueError异常。
Don't really understand why you had the isintance(i, int) in your base case. 不太了解为什么在基本案例中有isintance(i, int)

Simply use int(integer_string) 只需使用int(integer_string)

sums = {k: sum(int(i) for i in v) for k, v in size.items()}

Also, keep in mind using isinstance is typically considered an antipattern. 另外,请记住,使用isinstance通常被认为是反模式。 If you want type checking check out Python 3.6 type annotations or use a different language. 如果要进行类型检查,请查看Python 3.6类型注释或使用其他语言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM