如何计算出大于矩阵中某个阈值的值?

时间:2019-01-01 15:47:25

标签: python python-3.x numpy for-loop enumerate

假设我有一个矩阵:

a = [[4,7,2],[0,1,4],[4,5,6]] 

我想得到

b = [0, 1]
c = [[2],[0,1]]
  • b = [0,1]是因为a0位置的1的内部列表包含的值小于3
  • c = [[2],[0,1]]是因为[2]中第一个子列表的b nd元素低于3,而[0,1]是因为{{1 }}低于3。

我尝试过:

b

它仅返回原始矩阵。

如何在python中获得for i in a: for o in i: if o < 3: print(i) b

1 个答案:

答案 0 :(得分:0)

您可以利用enumerate(iterable[,startingvalue])来获得索引所迭代对象的值:

a = [[4,7,2],[0,1,4],[4,5,6]] 

thresh = 3
b = [] # collects indexes of inner lists with values smaller then thresh
c = [] # collects indexes in the inner lists that are smaller then thresh
for idx, inner_list in enumerate(a):
    if any(value < thresh for value in inner_list):
        b.append(idx)
        c.append([])
        for idx_2, value in enumerate(inner_list):
            if value < thresh:
                c[-1].append(idx_2)

print(a)
print(b)
print(c)

输出:

[[4, 7, 2], [0, 1, 4], [4, 5, 6]]
[0, 1]
[[2], [0, 1]]

Doku: