python - 添加列表中的数字但保留其他元素

标签 python python-3.x list sum

我有这个列表列表:

[["hari","cs",10,20],["krish","it",10],["yash","nothing"]]

我需要检查子列表中的数字并添加它们,即我想要这个输出:

[["hari","cs",30],["krish","it",10],["yash","nothing",0]]

我不知道该如何处理。

最佳答案

您可以迭代每个子列表并对数字求和(基于 isinstance 检查)并保持非数字不变:

l = [["hari","cs",10,20],["krish","it",10],["yash","nothing"]]
newl = []
for subl in l:
    newsubl = []
    acc = 0
    for item in subl:
        if isinstance(item, (int, float)):
            acc += item
        else:
            newsubl.append(item)
    newsubl.append(acc)
    newl.append(newsubl)
print(newl)
# [['hari', 'cs', 30], ['krish', 'it', 10], ['yash', 'nothing', 0]]

如果您喜欢生成器函数,可以将其拆分为两个函数:

l = [["hari","cs",10,20],["krish","it",10],["yash","nothing"]]

def sum_numbers(it):
    acc = 0
    for item in it:
        if isinstance(item, (int, float)):
            acc += item
        else:
            yield item
    yield acc

def process(it):
    for subl in it:
        yield list(sum_numbers(subl))

print(list(process(l)))
# [['hari', 'cs', 30], ['krish', 'it', 10], ['yash', 'nothing', 0]]

关于python - 添加列表中的数字但保留其他元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46036401/

相关文章:

python - 如何从表中选择 2 个不同的随机行?

python - 将 pandas 多索引数据框插入特定位置的另一个多索引数据框

python - 基于在 Pandas 中堆叠列来延长 DataFrame

javascript - JQuery 嵌套列表过滤器 - 当父级匹配时显示所有子级

c# - 合并两个列表并在合并时应用自定义函数

python - numpy.fftn 中哪些是高频项?

python - 在gekko中一起建模微分方程和线性方程?

python - 如何根据不同的索引阈值过滤数据帧

python + 写入文件的分号写在下一行

python - 如何使用 boolean 值退出 'for' 循环?