3

i wasn't able to find the answer using the search function so i am starting this thread.

Consider having a list that is divideable by x. For example:

onetonine = [1,2,3,4,5,6,7,8,9]

The example x would be 3 in this case.

Now i want to create a new list with

len(onetonine)/x

elements, which would mean 3 elements.

The important part is, that i want the elements of the new list to be the sum of every x elements of the old list. This means:

newlist = [6, 15, 24]

So basically take x=3 elements of my old list and add them. Repeat until done.

I wasn't able to get a working solution for this so i am asking for help.

Thank you.

TolleWurst
  • 51
  • 3
  • See: https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks or https://stackoverflow.com/questions/3992735/python-generator-that-groups-another-iterable-into-groups-of-n – FelixEnescu Dec 03 '17 at 16:16

5 Answers5

6

The following list comprehension of the sums of the appropriate slices will work:

>>> [sum(onetonine[i:i+3]) for i in range(0, len(onetonine), 3)]
[6, 15, 24]

Note: this will not discard any rest if the length of the original list is not divisible by the chunk length but just add the sum of the last (shorter) chunk.

user2390182
  • 72,016
  • 6
  • 67
  • 89
4

Using zip(*([iter(onetonine)]*3)) which splits the list into 3 sub-lists

onetonine = [1,2,3,4,5,6,7,8,9]
[sum(i) for i in zip(*([iter(onetonine)]*3))]
#[6, 15, 24]
Transhuman
  • 3,527
  • 1
  • 9
  • 15
0
def group_sums(lst, x): # use better name, no idea for me
    new = []
    for i in range(len(lst)//x):
        new.append(sum(lst[i*x:i*x+x]))
    return new

P.S.: I'm so happy it works, developed it right now :)

M. Volf
  • 1,259
  • 11
  • 29
0

I upvoted schwobaseggl but had something similar going on.

We could also check if mod equals 0:

x = 3

if len(onetonine) % x == 0:
    result = [sum(onetonine[i:i+x]) for i in range(0, len(onetonine), x)]
else:
    result = 'Error!'
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
0

You can also doing using map:

onetonine = [1,2,3,4,5,6,7,8,9]

newList = list(map(lambda index: sum(onetonine[index:index+3]), range(0,len(onetonine),3)))
print(newList)

Output:

[6, 15, 24]
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29