python - 如何在不使用for循环的情况下从数组列表中删除元素

标签 python python-3.x numpy

我有这个代码:

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/

相关文章:

python - 在Python中追加列表的问题

python - 在python中使用多个参数进行日志记录

python - 在 App Engine 上生成 GUID 的好方法?

python-3.x - NetworkX:在 DAG 中查找最长路径,返回最大的所有关系

python-3.x - 使用 flask 路由(Python)启动和停止方法

python - 使用 python 2.7 导入 numpy

python - 对特定列中的特定行求和

python - Django 查询详情 View

python - 从 。导入模型有效,但导入模型无效

python - 有效删除不同行之间包含重复元素的行