I have a nested list newlist
. I want to find the sum of values like '£2.99','£4.99'
. The effective sum would be like 2.99+4.99+2.99
etc
newlist = [['£2.99', '1', '16-Feb-19'], ['£4.99', '2', '16-Feb-19'], ['£2.99', '1', '15-Feb-19']....]
I have a nested list newlist
. I want to find the sum of values like '£2.99','£4.99'
. The effective sum would be like 2.99+4.99+2.99
etc
newlist = [['£2.99', '1', '16-Feb-19'], ['£4.99', '2', '16-Feb-19'], ['£2.99', '1', '15-Feb-19']....]
Try this:
sum([float(i[0].replace('£','')) for i in a])
As @darksky mentioned, I will explain here a little more:
sum
will returns the sum of one iterable item.
float
will cast Strings to float like "2.99"
--> 2.99
and Replace is obvious.
the output will be:
10.97
You can use a generator expression and sum
the first element in each list (simply slice it with [1:]
to skip the £
):
my_list = [['£2.99', '1', '16-Feb-19'], ['£4.99', '2', '16-Feb-19'],
['£2.99', '1', '15-Feb-19']]
sum(float(l[0][1:]) for l in my_list)
# 10.97
Use list comprehensions
to solve this:
l= [['£2.99', '1', '16-Feb-19'], ['£4.99', '2', '16-Feb-19'], ['£2.99', '1', '15-Feb-19']]
# 1. replace() will replace the first argument '£' with second argument (empty space).
# 2. map(): It takes two arguments, where first argument is the datatype
# you wish to convert to and second argument is value we want to convert.
# 3. list(): Since the list comprehension gives us the list of mapping, where as we need to
# convert it to proper proper list with numbers, and that's why we use list()
# to do so.
sum(list(map(float,[i[0].replace('£','') for i in l])))
10.97
Here's a different answer:
data = [['£2.99', '1', '16-Feb-19'], ['£4.99', '2', '16-Feb-19'], ['£2.99', '1', '15-Feb-19']]
sum = 0.0
for item in data:
formatted = item[0][1:]
sum += float(formatted)
After that code completes, sum
will be equal to 10.97, the result.