【问题标题】:How to multiply the two nearby elements in a list? [duplicate]如何将列表中的两个附近元素相乘? [复制]
【发布时间】:2019-05-30 20:41:37
【问题描述】:

我有一个如下列表:

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

我想保留前两个元素,然后将其余两个附近的元素相乘。 结果如下:

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

我知道如果我想要求和,我可以使用下面的代码:

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

我会得到结果:[1, 2, 7, 2*s + 1] 但是,我不知道如何获得乘法结果。 谢谢

【问题讨论】:

    标签: python list sum multiplication


    【解决方案1】:

    这是一个类似的方法,但使用 itertools.starmapoperator.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]
    

    【讨论】:

      【解决方案2】:

      定义一个自定义的乘法函数:

      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)))]
      

      【讨论】:

        【解决方案3】:

        也可以使用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]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-12-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-25
          相关资源
          最近更新 更多