【问题标题】:How to print the location/index of an item inside of a 2d array in python?如何在python中打印二维数组中项目的位置/索引?
【发布时间】:2020-12-07 18:47:09
【问题描述】:

我想识别图片中的一条直线(黑色/白色,0/1)并定位它,所以我已经用 numpy 将图片转换为二维数组,并通过计算单元格的平均值(a单元格是二维数组中的一行,请参见下面的源代码)。现在我想返回索引(不是值)或至少返回不是白色的单元格的位置。

我找到了一种在一维数组中执行此操作的方法,但是通过单元格比遍历每个像素值要快。直到现在我有这样的东西:

for cell in img_array:                              # the array is 2d and the values are 0 or 1
    cal_average(cell)                               # selfmade function to calculate the average
    if not cal_average(cell) == 1 :                 # condition to find the line
        print('line found, it is here:', location)  # not working outcome

希望你知道一些事情。提前致谢!

我要合并的来源:

How to get item's position in a list?

Iterating through a multidimensional array in Python

【问题讨论】:

  • 我不知道你在问什么。 “细胞”是一个没有定义的术语。输入没有明确定义,我不知道“位置”是什么。请发布 MCVE 并正确定义您的条款。
  • 这就是我将源放入的原因。单元格是二维数组中的一行,位置是我想要找出的。我不知道这个词,所以我只写了“位置”来描述我正在搜索的内容。就像我使用的术语要坚持的行或单元格的数量。
  • 你不应该期望人们去其他地方理解你的问题。请让它在未来自给自足。

标签: python arrays numpy


【解决方案1】:

如果我对问题的理解正确,您想打印二维数组中元素的索引(x 和 y 坐标)。

我会使用 numpy 来方便和高效地进行数组操作。

import numpy as np  # import numpy 
arr = np.array([[5,4,3],
        [7,6,1],
        [10,34,7]
                ]) # example array

xs, ys = np.where(arr == 7) # criteria to search (can be modified to other operators like !=, <, > etc..
# xs, ys are the x and y coordinates of the indexes where the item was found. x[0], y[0] would be the the first point and so on...

for x,y in zip(xs,ys):
    print("Found at:",x,y) # loop through to print values 

输出:

发现于:1 0

发现于:2 2

【讨论】:

  • 如果它解决了您的问题,请考虑接受答案。但是,如果您希望我添加一些内容,请随时提及。
  • 是的,它有效,谢谢。所以诀窍是澄清数组内部的条件并压缩输出以正确打印。
  • 没错。此外,如果您想将这些索引处的值更改为其他值,您可以简单地执行arr[ np.where(arr == 7) ] = YOUR_NEW_VALUE
  • 我只想打印第一个和最后一个值。我试过 print('Found between',x[0],y[0],'and',x[-1],y[-1]) 但我得到 IndexError: invalid index to scalar variable.
  • 应该是xs[0],ys[0],您使用的是x,而不是xs。 x 是循环值 xs 是要索引的数组
猜你喜欢
  • 1970-01-01
  • 2016-11-27
  • 2016-05-21
  • 1970-01-01
  • 1970-01-01
  • 2017-05-22
  • 2015-10-07
  • 2021-03-24
  • 1970-01-01
相关资源
最近更新 更多