【问题标题】:Python set a column in list of list 2D matrixPython在列表二维矩阵列表中设置一列
【发布时间】:2018-10-08 09:59:49
【问题描述】:

所以给定两个列表

y_new = (   165,     152,     145,    174)
pos_2D  = ( (2,3), (32,52), (73,11), (43,97) )

我想要这样的东西

pos_2D_new = setCol(2, y_new, pos_2D)

其中第 2 列是 Y 坐标。

pos_2D_new = ( (2,165), (32,152), (73,145), (43,174) )

如何在 Python 中将 1D 设置为 2D 元组?

【问题讨论】:

  • 所以你将元组的第二部分替换为y_new? “旧”第二项会发生什么?
  • 是的...我正在创建一个新元组,其中包含旧的 X 和新的 Y。

标签: python list matrix tuples


【解决方案1】:

您可以使用带有 zip 的生成器表达式:

pos_2D_new = tuple((x, y) for (x, _), y in zip(pos_2D, y_new))

使用您的示例输入,pos_2D_new 将变为:

((2, 165), (32, 152), (73, 145), (43, 174))

【讨论】:

    【解决方案2】:

    你可以这样做:

    pos_2D_new = [ (x, y2) for (x, _), y2 in zip(pos_2D, y_new) ]
    

    或者如果你想要一个元组:

    pos_2D_new = tuple((x, y2) for (x, __), y2 in zip(pos_2D, y_new))
    

    因此我们同时迭代pos_2Dynew,并且每次我们构造一个新的元组(x, y2)

    上面当然不是很通用,我们可以让它更通用,并允许指定替换什么项目,比如:

    def replace_coord(d, old_pos, new_coord):
        return tuple(x[:d] + (y,) + x[d+1:] for x, y in zip(old_pos, new_coord))
    

    所以对于 x 坐标,您可以使用 replace_coord(0, old_pos, new_x_coord) 而对于 y 坐标它是 replace_coord(1, old_pos, new_y_coord)。这也适用于三个或更多维度的坐标。

    【讨论】:

    • 谢谢威廉!太棒了!... :)
    【解决方案3】:

    这会给

    def setCol(idx, coords_1d, coords_nd):
        # recalling that indexing starts from 0
        idx -= 1
        return [
            c_nd[:idx] + (c_1d,) + c_nd[idx+1:]
            for (c_1d, c_nd) in zip(coords_1d, coords_nd)
        ]
    

    >>> setCol(2, y_new, pos_2D)
    [(2, 165), (32, 152), (73, 145), (43, 174)]
    

    【讨论】: