Python在列表2D矩阵的列表中设置一列
所以给出了两个列表Python在列表2D矩阵的列表中设置一列,python,list,matrix,tuples,Python,List,Matrix,Tuples,所以给出了两个列表 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元组?您可以将生成器表达式与zip一起使用
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元组?您可以将生成器表达式与
zip
一起使用:
pos_2D_new = tuple((x, y) for (x, _), y in zip(pos_2D, y_new))
通过示例输入,pos\u 2D\u new
将变成:
((2, 165), (32, 152), (73, 145), (43, 174))
您可以通过以下方式执行此操作:
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_2D
和ynew
,每次我们构造一个新的元组(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坐标,可以使用替换坐标(0,旧坐标,新坐标)
,而对于y坐标,可以使用替换坐标(1,旧坐标,新坐标)
。这也适用于三维或三维以上的坐标
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)
]
及
因此,您将元组的第二部分替换为
y\u new
?“旧的”第二项怎么办?是的。。。我正在用旧的X和新的Y创建一个新的元组。谢谢威廉!太棒了!…)
>>> setCol(2, y_new, pos_2D)
[(2, 165), (32, 152), (73, 145), (43, 174)]