-2

I'm writing a code which calculates the sum of the numbers beside it.

For example, list1 = [10, 20, 30, 40, 50], the new list = [30 (10+20), 60 (10+20+30), 90 (20+30+40), 120 (30+40+50), 90 (40+50)]. => final list = [30, 60, 90, 120, 90].

At the moment my idea was of using a for loop but it was totally off.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
rprogramr
  • 33
  • 1
  • 7

2 Answers2

0

You can do it by creating triplets using zip:

# pad for first and last triplet
lst = [0] + original + [0]
# summarize triplets
sums = [sum(triplet) for triplet in zip(lst, lst[1:], lst[2:])]

Example:

>>> original = [10, 20, 30, 40, 50]
>>> lst = [0] + original + [0]
>>> sums = [sum(triplet) for triplet in zip(lst, lst[1:], lst[2:])]
>>> sums
[30, 60, 90, 120, 90]
>>>
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
0

Check out this guy's flatten function What is the fastest way to flatten arbitrarily nested lists in Python?

Take the result of the flattened lists of lists and sum the collection normally with a for loop, or a library that provides a count utility for collections.

Community
  • 1
  • 1
hansod1
  • 314
  • 1
  • 4