代码之家  ›  专栏  ›  技术社区  ›  Aminoff

无库列表中整数的乘积

  •  3
  • Aminoff  · 技术社区  · 9 年前

    比如说,我不被允许使用图书馆。 当我试图垂直计算索引时,问题变得更难了。

    bigList = [[1, 2, 3, 4, 5],
               [1, 2, 3, 4, 5],
               [1, 2, 3, 4, 5],
               [1, 2, 3, 4, 5],
               [1, 2, 3, 4, 5]]
    

    有了numpy,我的问题的解决方案是:

    import numpy as np   
    print([np.prod(l) for l in zip(*bigList)])
    
    [1, 32, 243, 1024, 3125]
    

    然而,如果没有它,我的解决方案会更加混乱:

    rotateY = [l for l in zip(*bigList)]
    productList = [1]* len(bigList)
    count = 0
    for l in rotateY:
        for i in l:
            productList[count] *= i
        count += 1
    print(productList)
    
    [1, 32, 243, 1024, 3125]
    
    4 回复  |  直到 9 年前
        1
  •  2
  •   Chris    9 年前

    你可以迭代每一行,得到每一行的 n -第个元素,并将每个元素相乘:

    >>> from functools import reduce
    >>> 
    >>> def mul_lst(lst):
        return reduce(lambda x, y: x * y, lst)
    
    >>> 
    >>> bigList = [[1, 2, 3, 4, 5],
           [1, 2, 3, 4, 5],
           [1, 2, 3, 4, 5],
           [1, 2, 3, 4, 5],
           [1, 2, 3, 4, 5]]
    >>> 
    >>> [mul_lst([row[i] for row in bigList]) for i in range(len(bigList))]
    [1, 32, 243, 1024, 3125]
    

    任何 图书馆,包括 functools mul_lst

    >>> def mul_lst(lst):
        product = lst[0]
        for el in lst[1:]:
            product *= el
        return product
    
    >>> mul_lst([3, 3])
    9
    >>> mul_lst([2, 2, 2, 2, 2])
    32
    
        2
  •  1
  •   Błotosmętek    9 年前

    为什么不简单:

    productList = []
    for i in range(len(bigList[0]):
        p = 1
        for row in bigList:
            p *= row[i]
        productList.append(p)
    

    或者,对您的解决方案进行一点改进:

    productList = [1]* len(bigList[0])
    for row in bigList:
        for i, c in enumerate(row):
            productList[i] *= c
    
        3
  •  1
  •   Divakar    9 年前

    转置 嵌套列表,然后使用 reduce

    >>> [reduce(lambda a,b: a*b, i) for i in map(list, zip(*bigList))]
    [1, 32, 243, 1024, 3125]
    
        4
  •  0
  •   user2699    9 年前

    def prod(x):
      """ Recursive approach with behavior of np.prod over axis 0 """
      if len(x) is 1:
          return x
      for i, a_ in enumerate(x.pop()):
          x[0][i] *= a_
      return prod(x)