【问题标题】:Printing locations containing non-zero elements in Python在 Python 中打印包含非零元素的位置
【发布时间】:2022-12-31 15:02:05
【问题描述】:

以下代码打印行号solution1,其中至少有一个非零元素。但是,对应于这些行号,我还如何打印哪些位置具有非零元素solution2,如预期输出所示。?例如,行1在位置[1,3,4,6]有非零元素,行2在位置[0,2,3,5]有非零元素。

import numpy as np

A=np.array([[  0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ],
       [  0.        , 423.81345923,   0.        , 407.01354328,
        419.14952534,   0.        , 212.13245959,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ],
       [402.93473651,   0.        , 216.08166277, 407.01354328,
          0.        , 414.17017965,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ]])


solution1 = []
for idx, e in enumerate(A):
    if any(e): 
        solution1.append(idx)
print("solution 1 =",solution1)

当前输出是

solution 1 = [1,2]

预期的输出是

solution 1 = [1,2]
solution 2 = [[1,3,4,6],[0,2,3,5]]

【问题讨论】:

  • 你能请edit 提出一个清晰、准确的问题吗?也许可以推断出你的问题,但这是一个和回答网站。可以看How to Ask获取指导。

标签: python list numpy


【解决方案1】:

使用np.where 首先找到非零值的所有坐标,然后按行拆分 y 索引:

idx, idy = np.where(A)
np.split(idy, np.flatnonzero(np.diff(idx) != 0) + 1)
# [array([1, 3, 4, 6], dtype=int32), array([0, 2, 3, 5], dtype=int32)]

【讨论】:

  • 如何获得这种形式的输出:[[1,3,4,6],[0,2,3,5]]
猜你喜欢
  • 2023-02-09
  • 2016-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-03
  • 1970-01-01
相关资源
最近更新 更多