如何检查一个[2x2]矩阵是否在列表中,如果不是,就追加它:
import numpy as np
l = None
for i in range(10):
mat = np.random.randint(0, 2, size=4)
mat = mat.reshape(2,2)
if l is None:
l = [mat]
if mat not in l:
l.append(mat)
给予我一个错误:*** ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我可以这样做:
import numpy as np
l = None
for i in range(100):
mat = np.random.randint(0, 2, size=4)
mat = mat.reshape(2,2)
if l is None:
l = [mat]
tmp_diff = [np.max(np.abs(elem - mat)) for elem in l]
if np.min(tmp_diff) > 0:
l.append(mat)
但这似乎效率低下。
我怎样才能只将唯一的矩阵追加到列表中?
1条答案
按热度按时间xmjla07d1#
Numpy的矩阵等式不像常规列表那样执行,因为它在数组轴上操作。
相反,您可以依赖以下两种方法之一:
1)收集唯一的4项列表(依赖于列表相等性检查),并最终将列表的列表转换为每个形状为
(2, 2)
的数组的数组:2)一次创建所有子矩阵,并使用
np.unique
过滤掉重复项:样品输出: