如何对未知长度的嵌套列表中各子列表的最后元素求和?
Hey there! Let's break down what's causing your error and fix this up quickly.
What's Wrong with Your Current Code?
The issue is in this line:
addList.append(eglist[-1])
eglist[-1] grabs the last entire sublist from your main list (in your example, that's ["b",2,3.4]), not the last element of the current sublist i you're looping through. That's why addList ends up filled with lists instead of the float values you need—hence the TypeError when trying to sum them.
Fixed Version of Your Code
Just change eglist[-1] to i[-1] to target the last element of each individual sublist:
eglist = [["a", 1, 2.3],["b",2,3.4]] addList = [] for i in eglist: addList.append(i[-1]) # This gets the last element of the current sublist total = sum(addList) print(total) # Output: 5.7
A More Concise Approach
You can skip creating the intermediate addList entirely using a generator expression—it's cleaner and more efficient:
eglist = [["a", 1, 2.3],["b",2,3.4]] total = sum(sublist[-1] for sublist in eglist) print(total) # Output: 5.7
This directly iterates over each sublist, grabs its last element, and sums them up in one go.
内容的提问来源于stack exchange,提问作者Nithila Logathas

