How can one convert a list of list
into int
, and then add them up?
The current result is [[1],[2],[3],[4]]
. I would like to remove those []
and them add them up into a single int
.
Thank you.
How can one convert a list of list
into int
, and then add them up?
The current result is [[1],[2],[3],[4]]
. I would like to remove those []
and them add them up into a single int
.
Thank you.
How about that
l = [[1],[2],[3],[4]]
def value(l):
return sum([i[0] for i in l])
print value(l)
OR
sum(sum(l, [])) #works on lists of lists only.
You could try this:
def Flatten(*args):
for x in args:
if hasattr(x, '__iter__'):
for y in Flatten(*x):
yield y
else:
yield x
output = sum(Flatten(input))
I would normally call this a duplicate because what you are looking for is how to flatten a list.
But the answer is using list comprehension which makes a little too difficult to read.
Here is their answer:
>>> list = [[1],[2],[3],[4]]
>>> [item for sublist in list for item in sublist]
[1, 2, 3, 4]
Here it is simplified
anotherList = []
for item in list:
for anotherItem in item:
anotherList.append(anotherItem)
print anotherList
Now adding:
def sumList(aList):
result = 0
for i in aList:
result+=i
return result
print sumList(anotherList)
Assuming you have a list of list of int
You can do this by using a for loop
>>> vList = [[1],[2],[3],[4]]
>>> vsum = 0
>>> for x in vList:
... for y in x:
... vsum += y
...
>>> vsum
10
Or you can do this by list comprehension
>>> sum([y for x in vList for y in x])
10