简体   繁体   English

如何打印包含单独的列表总和的列表

[英]how to print a list containing the separate sums of lists

I'm trying to gain the sum of a list of lists where the output would be [6,2,10] for the defined lists below. 我试图获取列表清单的总和,其中下面定义的列表的输出为[6,2,10]。

data = [[1,2,3], [2], [1, 2, 3, 4]]
output =[]
total = 0
for row in data:
  for val in row[0:len(row)]:
   total += val
output.append(total)
print(output)

However, the results of this program is [6, 8, 18]. 但是,该程序的结果为[6,8,18]。 Any help would be appreciated. 任何帮助,将不胜感激。

Use a list comprehension . 使用list comprehension

Each element in list is iterable , this fact makes sum the best option for this task. 列表中的每个元素都是可迭代的 ,这个事实使sum是此任务的最佳选择。

>>> data = [[1,2,3], [2], [1, 2, 3, 4]]
>>> [sum(d) for d in data]
[6, 2, 10]

Now, if you want to know what was your problem... 现在,如果您想知道问题出在哪里...

Place the accumulator after the data loop, and feed the list after every row loop: 累加器放置在数据循环之后,并在每个循环之后输入列表

>>> data = [[1,2,3], [2], [1, 2, 3, 4]]
>>> output = []
>>> for row in data:
...     total = 0
...     for val in row[0:len(row)]:
...         total += val
...     output.append(total)
...
>>> output
[6, 2, 10]

Use map() : 使用map()

data = [[1,2,3], [2], [1, 2, 3, 4]] 
print(list(map(sum, data)))
# [6, 2, 10]

Or list-comprehension: 或列表理解:

data = [[1,2,3], [2], [1, 2, 3, 4]]
print([sum(x) for x in data])
# [6, 2, 10]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM