如何在不使用forloop的情况下从数组的列表中删除元素

2024-09-27 09:30:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码:

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]]

我想按顺序从portes列表中删除premier_choix列表的每个元素(从portes[0][0]中删除premier_choix[0][0],而不使用for循环。你知道吗


Tags: 元素密码列表forsize顺序nprange
3条回答

我假设总有一个元素要删除(就像上面的例子)。输入:

# Import
import numpy as np

# Input
portes = [[0, 1, 2]] * 20
premier_choix = np.random.choice(range(3), size=(1, 20))

# Modify input (or start with it)
portes = np.array(portes)
premier_choix = premier_choix.reshape(-1, 1)

矢量化解决方案:

output = portes[portes != premier_choix].reshape(-1, 2)
print(output)

您可以使用.remove()完全删除列表

可以使用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]])

相关问题 更多 >

    热门问题