我要在另一个矩阵中插入一个矩阵(str)。
HM =
[['', '', '', '', ''],
['', '', '', '', ''],
['', '', '', '', ''],
['', '', '', '', ''],
['', '', '', '', ''],
['', '', '', '', ''],
['', '', '', '', '']]
B = [["AA", "BB"],["CC","DD"]]
offset = (1,2)
结果应为:
[['', '', '', '', ''],
['', '', 'AA', 'BB', ''],
['', '', 'CC', 'DD', ''],
['', '', '', '', ''],
['', '', '', '', ''],
['', '', '', '', ''],
['', '', '', '', '']]
在jupyter笔记本3.7版上工作,尝试过np.insert,尝试过HM + B,尝试过np斜杠
HM = [[""]*15]*10
B = [["BBB"]*3, ["CCC"]*3, ["DDD"]*3]
offsetx = 2
offsety = 1
for x in range(1, 1 + offsetx):
for y in range(2, 2 + offsety):
HM[x][y] = B[x][y]
HM
答案 0 :(得分:1)
您可以使用列表理解:
HM = [['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', '']]
B, offset = [["AA", "BB"],["CC","DD"]], (1, 2)
_b = iter(B)
new_data = [a[:offset[-1]]+(lambda x:x+a[len(x)+offset[-1]:])(next(_b)) if offset[0] <= i <= (offset[0]+len(offset)-1) else a
for i, a in enumerate(HM)]
输出:
[['', '', '', '', ''],
['', '', 'AA', 'BB', ''],
['', '', 'CC', 'DD', ''],
['', '', '', '', ''],
['', '', '', '', ''],
['', '', '', '', ''],
['', '', '', '', '']]
答案 1 :(得分:0)
在double for循环中按索引访问元素。
给出矩阵:
HM = [['', '', '', '', ''],
['', '', '', '', ''],
['', '', '', '', ''],
['', '', '', '', ''],
['', '', '', '', ''],
['', '', '', '', ''],
['', '', '', '', '']]
您可以通过这种方式插入子矩阵,例如:
B = [["AA", "BB"],["CC","DD"]]
offset = (1,2)
for x, row in enumerate(B):
for y, e in enumerate(row):
HM[x + offset[0]][y + offset[1]] = e
for row in HM:
print(row)
# ['', '', '', '', '']
# ['', '', 'AA', 'BB', '']
# ['', '', 'CC', 'DD', '']
# ['', '', '', '', '']
# ['', '', '', '', '']
# ['', '', '', '', '']
# ['', '', '', '', '']
答案 2 :(得分:0)
如第一条语句所述,我无法使用较大的矩阵(使用20x20和5x6矩阵)解决问题。我最终使用了3个矩阵-一个额外的np.array在前两个之间切换访问。所有其他解决方案均无效-恕我直言,有一个严重的错误应解决,但这将显示出一些“研究成果” ...