我有这个代码:
portes = [[0, 1, 2]] * 20
bonnes_portes = np.random.choice(range(3), size=(1, 20))
premier_choix = np.random.choice(range(3), size=(1, 20))
print(portes)
print(premier_choix)
此输出:
[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]
[[1 1 1 2 2 1 1 2 2 1 0 0 1 2 0 0 1 2 1 2]]
我想删除 premier_choix
的每个元素列表来自portes
按顺序列出(从 premier_choix[0][0]
中删除 portes[0][0]
...)不使用 for 循环。
最佳答案
您可以使用np.argwhere
参数来获取相关索引,然后对数组使用切片操作并将其重新整形回所需的形式。
portes_arr = np.array(portes)
idx = np.argwhere(portes_arr != np.array(premier_choix).reshape(20,1))
portes_arr[idx[:,0], idx[:,1]].reshape(20,2)
(示例-)输入
premier_choix
array([[2, 1, 0, 1, 1, 2, 2, 1, 1, 1, 1, 2, 1, 0, 1, 2, 2, 2, 1, 1]])
输出
portes_arr[idx[:,0], idx[:,1]].reshape(20,2)
array([[0, 1],
[0, 2],
[1, 2],
[0, 2],
[0, 2],
[0, 1],
[0, 1],
[0, 2],
[0, 2],
[0, 2],
[0, 2],
[0, 1],
[0, 2],
[1, 2],
[0, 2],
[0, 1],
[0, 1],
[0, 1],
[0, 2],
[0, 2]])
关于python - 如何在不使用for循环的情况下从数组列表中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57548118/