Skip to main content
 首页 » 编程设计

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

2025年02月15日7TianFang

我有这个列表列表:

[["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]]