You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对未知长度的嵌套列表中各子列表的最后元素求和?

How to Sum the Last Float Element of Each Sublist in a Nested List

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:59:02