【问题标题】:List of lists filled with elements/rows of a list subtracted from one another列表的列表填充了一个列表的元素/行,彼此相减
【发布时间】:2018-11-17 10:13:00
【问题描述】:

所以我有一个 Nx1 列表,其中每一行 (i->I) 应该从形成列表的所有其他元素中减去,然后这个列表应该是另一个包含 I 行的列表。目前我一直在使用循环执行此操作,但想知道是否可以通过广播来消除对循环的要求,有点像 scipy 中的 pdist/cdist 工作方式。

例如:

An input matrix of: [1,2,4,7,9] 
should result in: [[0,1,3,6,8],[-1,0,2,5,7],[-3,-2,0,3,5],[-6,-5,-3,0,2],[-8,-7,-5,-2]]

谢谢!

【问题讨论】:

    标签: python list scipy broadcast subtraction


    【解决方案1】:

    使用numpy 编写它当然有更好的方法,但这是一种方法:

    将 numpy 导入为 np

    input = [1,2,4,7,9]
    
    m = np.array(input * len(input)).reshape(len(input), len(input))
    m - np.array(input).reshape(len(input), 1)
    
    # array([[ 0,  1,  3,  6,  8],
    #        [-1,  0,  2,  5,  7],
    #        [-3, -2,  0,  3,  5],
    #        [-6, -5, -3,  0,  2],
    #        [-8, -7, -5, -2,  0]])
    

    【讨论】:

      【解决方案2】:

      如果anumpy.array,那么最简单的解决方案是使用numpy.newaxis

      >>> a=numpy.array([1,2,4,7,9])
      >>> a-a[:,numpy.newaxis]
      array([[ 0,  1,  3,  6,  8],
             [-1,  0,  2,  5,  7],
             [-3, -2,  0,  3,  5],
             [-6, -5, -3,  0,  2],
             [-8, -7, -5, -2,  0]])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        相关资源
        最近更新 更多