在列表中添加数字但保留其他元素

时间:2017-09-04 11:48:47

标签: python python-3.x list sum

我有这个列表清单:

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

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

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

我不知道如何处理这个问题。

5 个答案:

答案 0 :(得分:1)

您可以迭代每个子列表并对数字求和(基于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]]

答案 1 :(得分:0)

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

d1=[]               #result
for x in d:       
    m=[]            #buffer for non int
    z=0             # int sum temp var
    for i in x:
        if str(i).isdigit():   #check if element is an int
            z+=i
            #print z
        else:
            m.append(i)
    m.append(z)           #append sum
    d1.append(m)          #append it to result
print d1

答案 2 :(得分:0)

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

new_list = []
for list_item in lists:
    new   = []
    count = 0
    for item in list_item:
        if type( item ) == int:
            count = count + item
        else:
            new.append( item )
    new.append( count )
    new_list.append( new )

print( new_list )

答案 3 :(得分:0)

试试这个:

l = [["hari","cs",10,20],["krish","it",10],["yash","nothing"]]
sums = [sum([x for x in _l if type(x) == int]) for _l in l]
without_ints = map(lambda _l: filter(lambda x: type(x) == int, _l, l))
out = [w_i + [s] for (s, w_i) in zip(sums, without_ints)]
>>> out
[['hari', 'cs', 30], ['krish', 'it', 10], ['yash', 'nothing', 0]]

希望它有所帮助!

答案 4 :(得分:0)

这是我写过的最大的一个班轮..

假设这些数字都在每个列表的末尾,这应该可以解决问题!

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

new_list = [[element if type(element) != int else sum(inner_list[inner_list.index(element):]) for element in inner_list if type(inner_list[inner_list.index(element) - 1 if type(element) == int else 0]) != int] for inner_list in my_list]

print(new_list)  # [['hari', 'cs', 30], ['krish', 'it', 10], ['yash', 'nothing']]