Home > OS >  Sum of list of lists of lists based on indexes
Sum of list of lists of lists based on indexes

Time:08-19

I have a dataset as follow:

[['HG00096', [15, 1, 0]], ['HG00097', [33, 0, 0]], ['NA21127', [24, 1, 0]]]

And I would like to have to sum of the first values in the list of each list (i.e. 15 33 24 = 72). So far, using list comprehension and with this post, I tried this line but with no success.

[sum([x[1][0] for x in i]) for i in testdic]

What am I doing wrong here ? Thanks a lot

CodePudding user response:

You are iterating through the elements of each sublist, then trying to still index twice, meaning you end up indexing an int.

Instead you can simply apply your index to each element of the list.

sum(x[1][0] for x in testdic)
  • Related