2017-09-04 121 views
2

我列出这个清单:添加数字在列表中,但保留其他元素

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

我需要检查的子列表号和添加它们,也就是我想这样的输出:

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

我不知道如何解决这个问题。

+0

数字总是在每个列表的末尾? –

+0

是的@StamKaly,你说得对。 – Gayathri

回答

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]] 
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 
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) 
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]] 

希望它有帮助!

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']] 
相关问题