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.
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]. Any help would be appreciated.
Use a list comprehension
.
Each element in list is iterable , this fact makes sum
the best option for this task.
>>> 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()
:
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.