-3

(Python) Hey, how to separate different values of a list as follows?

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

into

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

and then perform addition so that the resultant list is:

list3=[[3],[7],[11],[15],[19]]

Thanks for helping !

  • Have you tried something yourself? The first part is a well known [duplicate](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks). The second part is simply `[[sum(x)] for x in list2]`. – timgeb May 02 '20 at 08:22
  • @timgeb yes i did, but it didnt work at all , it was a disaster lol, thats why im looking for help... – Aaryansh Sahay May 02 '20 at 08:23
  • Alright, just include it the next time no matter how disastrous. You are risking downvotes/closure otherwise. – timgeb May 02 '20 at 08:31

2 Answers2

2

You can do the following:

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

it = iter(list1)
list2 = list(zip(it, it))
# alternative using slices:
# list2 = [list1[i:i+2] for i in range(0, len(list1), 2)]

list3 = [[a+b] for a, b in list2]

Or do it all in one step:

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
it = iter(list1)
list3 = [[sum(l)] for l in zip(it, it)]
# or flat:
# list3 = list(map(sum, zip(it, it)))  # flat
user2390182
  • 72,016
  • 6
  • 67
  • 89
1

One way is to use numpy:

import numpy as np 
np.array(list1[::2])+np.array(list1[1::2])

Result:

array([ 3,  7, 11, 15, 19])

If you want two dimensions, you can reshape it.

If you want to do it without numpy, here a simple implementation:

A = list1[::2]
B = list1[1::2]
result = []
for i in range(len(A)):
    result.append([A[i]+B[i]])

Result:

[[3], [7], [11], [15], [19]]
Code Pope
  • 5,075
  • 8
  • 26
  • 68