简体   繁体   English

将以空格分隔的整数求和为列表中的字符串

[英]Sum space-separated integers as string in a list

I currently have this list: ['5 4 7', '4 3 1', '6 8 4'', '4 8 6'] Note that not all numbers are separated by commas. 我目前有这个列表: ['5 4 7', '4 3 1', '6 8 4'', '4 8 6']请注意,并非所有数字都以逗号分隔。

I would like to be able to calculate the total for each section of the list. 我希望能够计算列表中每个部分的总数。 For example, the first calculation should be 5+4+7 to give me 16. I would just like to know how to convert this list to be able to do maths calculations with the numbers. 例如,第一次计算应该是5 + 4 + 7给我16.我只想知道如何转换这个列表,以便能够用数字进行数学计算。

split your strings, map to integer and perform sum on the resulting inputs, in a list comprehension: 在列表解析中拆分字符串,映射到整数并对结果输入执行sum

>>> [sum(map(int,x.split())) for x in ['5 4 7', '4 3 1', '6 8 4', '4 8 6']]
[16, 8, 18, 18]

(works for negative values as well :)) (适用于负值:))

You can also use regex: 你也可以使用正则表达式:

import re
s = ['5 4 7', '4 3 1', '6 8 4', '4 8 6']
new_s = [sum(map(int, re.findall('\d+', b))) for b in s]

Output: 输出:

[16, 8, 18, 18]

However, if every digit is a single character, then you can use isdigit() : 但是,如果每个数字都是单个字符,那么您可以使用isdigit()

last_result = [sum(map(int, filter(lambda x:x.isdigit(), i))) for i in s]

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

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