【问题标题】:How do I figure out the value which is greater than certain threshold in a matrix?如何找出矩阵中大于某个阈值的值?
【发布时间】:2019-01-01 15:47:25
【问题描述】:

假设我有一个矩阵:

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

我想得到

b = [0, 1]
c = [[2],[0,1]]
  • b = [0,1] 因为a 在位置01 的内部列表包含小于3 的值。
  • c = [[2],[0,1]] 因为b 中第一个子列表的[2] nd 元素低于3,[0,1] 因为b 中第二个子列表中的第一个和第二个元素低于3。

我试过了:

for i in a:
   for o in i:
      if o < 3:
         print(i)

它只返回原始矩阵。

如何在 python 中获取b&c

【问题讨论】:

  • "矩阵b是a[0],a[1]的值小于3,c是a[0][2]和a[0][0],a [0][1] 小于 3"。这根本没有使问题听起来很清楚
  • 这并没有以您正在寻找的确切形式给出它,但根据您想要这样做的原因,您可能对输出元组 ([0,1,1],[2,0,1])np.where(a&lt;3) 感兴趣a&lt;3. 所在的索引

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


【解决方案1】:

您可以利用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]]

独库:

【讨论】:

    猜你喜欢
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多