给定矩阵和范围,找到子矩阵中不同元素数量的最佳方法是什么?我试过了:
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))
E.g)
给定的矩阵:
1 2 3
3 2 1
5 4 6
鉴于:
a = 1, b= 1, c = 2, d = 3
答案应为3,因为子矩阵1,1到2,3
中只有3个不同的元素还有其他pythonic方式吗?
答案 0 :(得分:1)
from itertools import chain
set(chain.from_iterable([t[b-1:d] for t in l[a-1:c]]))
# len(...) this should get the length
答案 1 :(得分:1)
您可以在不使用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.