0
list1 = [['hello',3],['bye',4].....]

I need to find just the sum of the numbers, 3 + 4 = 7 in this case, for an undefined number of item in the list all structured like this

I don't know how to call a spisific element from the sublists from every sublist for a sum command. I have tryed the following but what do I put in the first brackets? Or is there a better way to write this?

sum(list1[][1])

Thanks!!

  • Welcome to SO. Unfortunately this isn't a discussion forum, tutorial or code writing service. Please take the time to read [ask] and the links it contains. You should spend some time working your way through [the Tutorial](https://docs.python.org/3/tutorial/index.html), practicing the examples. It will give you an introduction to the tools Python has to offer and you may even start to get ideas for solving your problem. – wwii Nov 10 '17 at 21:49

1 Answers1

0

For a simple two dimensional list, you can try this:

list1 = [['hello',3],['bye',4]]
the_sum = sum(i[-1] for i in list1)

However, for a list of n dimensions, recursion is best:

list1 = [['hello',3],['bye',4], [["hi", 19], ["yes", 18]]]

def flatten(s):
   if not isinstance(s, list):
       yield s
   else:
       for i in s:
          for b in flatten(i):
              yield b

final_result = sum(filter(lambda x:isinstance(x, int), list(flatten(list1))))

Output:

44
Ajax1234
  • 69,937
  • 8
  • 61
  • 102