我正在尝试编写代码,该代码将为我们提供子列表总和的列表。例如,如果输入的列表是[[5,4],[2,1,7],[1]],我们将得到它作为回报[9,10,1]。 考虑到我们尚未学习求和函数,我的老师要求不要使用求和函数。 我目前有一个代码,但是有些事情我不确定,它会不断返回一个空列表。
这就是我所拥有的:
def sumSublist(inital_list):
i = 0
initial_list = list()
finalList = []
while i < len(initial_list):
sublist = list[i]
for j in sublist:
sublistsum = 0
sublistsum += j
finalList.append(sublistsum)
i += 1
return finalList
print(sumSublist([[5, 4], [2, 1, 7], [1]]))
,它打印:[] 任何帮助或建议将极大地帮助您
答案 0 :(得分:4)
您的解决方案存在几个问题:
initial_list
,而不是inital_list
。initial_list[i]
,这是不正确的:list[i]
。initial_list = list()
(这就是结果为空的原因。)sublistsum = 0
,这就是为什么该部分必须在内部循环之前 的原因。finalList.append(sublistsum)
行必须在内部循环之后 。这应该解决问题:
def sumSublist(initial_list):
i = 0
finalList = []
while i < len(initial_list):
sublist = initial_list[i]
sublistsum = 0
for j in sublist:
sublistsum += j
finalList.append(sublistsum)
i += 1
return finalList
但是,如果我们一直使用for
,则可以简化上述解决方案:
def sumSublist(initial_list):
finalList = []
for sublist in initial_list:
sublistsum = 0
for num in sublist:
sublistsum += num
finalList.append(sublistsum)
return finalList
但是在现实生活中,我们应该使用sum
并列出理解,这就是我们用Python编写惯用的解决方案的方式:
def sumSublist(initial_list):
return [sum(sublist) for sublist in initial_list]
无论如何,它可以按预期工作:
sumSublist([[5, 4], [2, 1, 7], [1]])
=> [9, 10, 1]
答案 1 :(得分:2)
您可以考虑首先定义对数字列表进行操作的sum
函数,然后将其应用于initial_list
的每个列表(在我的示例中为xss
):
def sum(xs):
# traverse each element of xs
# and return the sum
def sum_sublist(xss):
# traverse each element of xss
# which are lists, apply the `sum` function
# defined above on each, and return the list of the sums
答案 2 :(得分:-2)
如果它只是一个带有一层嵌套列表的列表,则可以轻松地执行此操作:
正常方式:
lst = [[1,2],[1,2,3], [1]]
summed = [[sum(i)] for i in lst]
不使用sum()
# this does the same thing but in reference to what you were talking about
def sumSubList(lst):
summed = []
for i in lst:
summ = 0
for x in i: summ += x
summed.append([summ])
return summed
print(sumSubList(lst))