我有这个列表:
[["hari","cs",10,20],["krish","it",10],["yash","nothing"]]我需要检查子列表中的数字并添加它们,例如,我需要以下输出:
[["hari","cs",30],["krish","it",10],["yash","nothing",0]]我不知道如何处理这个问题。
发布于 2017-09-04 19:55:11
您可以迭代每个子列表并对数字求和(基于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]]发布于 2017-09-04 19:57:09
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发布于 2017-09-04 19:58:23
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 )https://stackoverflow.com/questions/46036401
复制相似问题