numpy 仅将唯一矩阵追加到列表

z4iuyo4d  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(76)

如何检查一个[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)

但这似乎效率低下。
我怎样才能只将唯一的矩阵追加到列表中?

xmjla07d

xmjla07d1#

Numpy的矩阵等式不像常规列表那样执行,因为它在数组轴上操作。
相反,您可以依赖以下两种方法之一:

1)收集唯一的4项列表(依赖于列表相等性检查),并最终将列表的列表转换为每个形状为(2, 2)的数组的数组:

mtx_list = []

for i in range(10):
    lst = np.random.choice(2, size=4).tolist()
    if lst not in mtx_list:
        mtx_list.append(lst)

mtx_list = np.array(mtx_list).reshape(-1, 2, 2)
print(mtx_list)

2)一次创建所有子矩阵,并使用np.unique过滤掉重复项:

mtx_list = np.array([np.random.choice(2, size=(2,2)) for i in range(10)])
mtx_list = np.unique(mtx_list, axis=0)
print(mtx_list)

样品输出:

[[[0 0]
  [0 0]]

 [[0 0]
  [0 1]]

 [[0 1]
  [0 1]]

 [[0 1]
  [1 0]]

 [[0 1]
  [1 1]]

 [[1 0]
  [0 1]]

 [[1 1]
  [1 1]]]

相关问题