给定一个矩阵和一个范围,查找子矩阵中不同元素数量的最佳方法是什么?我尝试过:
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/