Reputation: 3388
I have a list like this:
a = ['1 MB', '2 MB']
I want to sum all the elements in a.
I figured I first have to create integer list and use sum() function. How can I do that?
Upvotes: 0
Views: 107
Reputation: 4903
This would work for differing multipliers:
import re
pattern = "(\d+)\s*(\w+)?"
a = ['1 MB', '2 MB', '3 K', '250' ]
multiplier = { None: 1, 'MB' : 1000000, 'K' : 1000 }
def multi(m):
if m:
return int(m.group(1)) * multiplier[m.group(2)]
else:
return 0
r = map(multi, [ re.search(pattern, x) for x in a])
print r
print sum(r)
With the following output:
[1000000, 2000000, 3000, 250]
3003250
Upvotes: 0
Reputation: 170279
Use the built-in split
to separate the number from the rest of the string
>>> a = ['1 MB', '2 MB']
>>> sum([int(s.split(' ')[0]) for s in a])
3
s.split(' ')
creates the list ['1', 'MB']
Or use a generator expression to avoid the unneeded list that the list comprehension creates:
>>> a = ['1 MB', '2 MB']
>>> sum(int(s.split(' ')[0]) for s in a)
3
Upvotes: 2
Reputation: 251186
you can use regex
here:
In [19]: a = ['1 MB', '2 MB']
In [20]: sum(int(re.search(r'\d+',x).group()) for x in a)
Out[20]: 3
where re.search(r'\d+')
returns something like:
In [23]: [re.search(r'\d+',x).group() for x in a]
Out[23]: ['1', '2']
Upvotes: 0
Reputation: 32308
Assuming all of the elements end in ' MB'
, you can do this:
sum(map(int, (x[:-3] for x in a)))
Breakdown:
(x[:-3] for x in a)
takes all but the last three characters of the string.map(int, iterable)
'maps' the int
function to each element of the iterable.sum(iterable)
simply sums the elements of the iterable.Upvotes: 1