1

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.

mech
  • 2,775
  • 5
  • 30
  • 38
Kelly Wang
  • 21
  • 3
  • 1
    Have you tried to iterate through your list of lists yet? (Iterating on lists typically looks like `for elem in somelist:...` If you did, what happened? If not, give it a shot and post back your results. I'm sure we can help guide you through something that will work. – erewok Feb 24 '16 at 04:20

4 Answers4

1

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.
Kamlesh
  • 2,032
  • 2
  • 19
  • 35
0

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))
konrad
  • 3,544
  • 4
  • 36
  • 75
0

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)
Community
  • 1
  • 1
Cripto
  • 3,581
  • 7
  • 41
  • 65
0

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
Praveen
  • 8,945
  • 4
  • 31
  • 49