-5

Lets say x has three samples: 2, 3, 4 y has four samples: 5, 6, 7, 8 In terms of coding, how do I add these samples in order to get 7, 9, 11, 8

1 Answers1

0

Welcome! I'm guessing there's probably a bit more to this request but if you want to add the two lists in the way you describe you can use zip.

Set up the lists

x = [2, 3, 4]
y = [5, 6, 7]

You can add them like this

print([sum(k) for k in zip(x, y)])

You get this output

[7, 9, 11]

EDIT - Adding to account for different list lengths

The original request from [2, 3, 4] and [5, 6, 7, 8] had a result of [7, 9, 11, 8]. To achieve this result with 8 on the end, the first list needs to be 'padded' with a 0. You'll notice that in the above, the 8 was brought forward.

Set up the lists

x  = [2, 3, 4]
y = [5, 6, 7, 8]

Add lists to list

ls_start = []
ls_start.append(x)
ls_start.append(y)

From the list of lists work out the max length of lists

max_len = max(map(len, ls_nums))

We will use this to work out how much to 'pad' the shorter lists by

Create a list to hold the 'padded' lists, this will be the final list we use to do cross wise addition

ls_final = []

Iterate through the lists padding those which are need padding

for ls in ls_nums:
    if len(ls) < max_len:

        extend = max_len - len(ls) 
        for add in range(extend): 
            ls.append(0)
        ls_final.append(np.array(ls))
    else: 
        ls_final.append(np.array(ls))

If you look at ls_final you'll see it contains

[array([2, 3, 4, 0]), array([5, 6, 7, 8])]

Add the list of arrays

ls_sum = np.zeros(max_len)

for ls in ls_final:
    ls_sum += ls

If you look at ls_sum, you'll see

array([ 7.,  9., 11.,  8.])

You can convert to a list

ls_sum.tolist()

To get this

[7.0, 9.0, 11.0, 8.0]

This method allows for any number of lists.

the_good_pony
  • 490
  • 5
  • 12