python - 使用python查找子矩阵中不同元素数量的最佳方法

标签 python matrix

给定一个矩阵和一个范围,查找子矩阵中不同元素数量的最佳方法是什么?我尝试过:

for i in l[a-1:c]: #a is the start row and c is the end row
            s.extend(set(i[b-1:d]))  #b is the start column and d is the end column
     print len(set(s))

例如)

给定矩阵:

1 2 3
3 2 1
5 4 6

给定:

a = 1, b= 1, c = 2, d = 3

答案应该是 3,因为子矩阵 1,1 到 2,3 中只有 3 个不同的元素

还有其他Pythonic方法可以做到这一点吗?

最佳答案

您可以完成所需的所有切片,而无需使用 for 循环(见下文)。我使用 Counter 模块来计算剩余子矩阵中唯一项目的数量。

from collections import Counter
import numpy as np

mat=[[1,2,3],[3,2,1],[5,4,6]]
mat = np.matrix(mat)

submat = mat[a-1:c,b-1:d] # extract the sub matrix desired

flattened = np.array(submat.flatten()).flatten() #flatten it for use in counter

print Counter(flattened) # prints the counts of each unique item

len_unique = len(Counter(flattened)) # the total number of unique items.

关于python - 使用python查找子矩阵中不同元素数量的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20453277/

相关文章:

r - 对两个矩阵应用函数

matlab - 如何将一个矩阵存储在另一个矩阵的一行中?软件

python - 围绕 twisted 的 IRC 客户端编写一个阻塞包装器

python - 使用按需 HOT Insight 集群从 Azure 数据工厂 V2 访问数据湖

python - 抓取 Amazon 作业结果时不断收到连接重置错误 10054

javascript - 谷歌地图距离矩阵和融合表

python - 使用另一个多索引系列屏蔽数据框

python - 如何将 numpy 安装到 Python 3.5?

c - 遍历矩阵的相邻对角线

arrays - 数组中的 Fortran 数组