简体   繁体   中英

Sum of list of lists of lists based on indexes

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 (ie 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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM