1

I have a list like below:

a = [ 1, 2 , 3, 4, s, s+1] 

I want to keep the first two elements and then multiply the rest two nearby elements. The result would be like below:

b = [1, 2, 12, s**2 + s]

I know if I want the summation, I can use the code below:

b = [*a[:2], *map(sum, (a[i: i + 2] for i in range(2, len(a), 2)))]
print (b)

and I will get the result which is : [1, 2, 7, 2*s + 1] However, I don't know how to get the multpilication result. Thanks

Hey There
  • 275
  • 3
  • 14

3 Answers3

3

Here's a similar approach, but instead using itertools.starmap with operator.mul:

from operator import mul
from itertools import starmap

s= 5
a = [ 1, 2 , 3, 4, s, s+1] 

[*a[:2], *starmap(mul, (a[i: i + 2] for i in range(2, len(a), 2)))] 
# [1, 2, 12, 30]
yatu
  • 86,083
  • 12
  • 84
  • 139
2

Define a customized multiplication function:

def mul(lst):
    s = 1
    for x in lst:
        s *= x
    return s

[*a[:2], *map(mul, (a[i: i + 2] for i in range(2, len(a), 2)))]
knh190
  • 2,744
  • 1
  • 16
  • 30
1

Can also use zip:

a = list(range(1, 11))

b = a[:2] + [x*y  for x, y in zip(a[2::2], a[3::2])]
b
[1, 2, 12, 30, 56, 90]
Lante Dellarovere
  • 1,838
  • 2
  • 7
  • 10