当我使用 for 循环进行迭代时,有没有办法在嵌套列表中找到子列表的索引?

我有一个二维数组,其中子列表的索引是 y 坐标,子列表中的元素是 x 坐标。

nested_lst = [ [32.6,45.1,22.1,...,36.8],[41.5,33.2,...],[12.8,37.8,[34.4,35.1,...] ]

这是一个大数组 - (2048,2098) - 浮点数。我想绘制一个散点图,其中点是满足 if item > 45 等条件的元素。

到目前为止我有这个:

xcoord = []
ycoord = []

for sublist in nested_lst:
    for (index,item) in enumerate(sublist):
        if item > (45):
            xcord.append(index)
            ycord.append(nested_lst.index(sublist))

我运行它,但它给了我这个错误信息:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

不确定我是否应该提到嵌套列表是 FITS 文件中 ccd 图像的数据数组,我已将其放大到中心以聚焦在对象上。我制作这个散点图的目的是让我可以测量图像的某些特征,所以我想首先绘制特征边界的图,因为我可以通过它们的亮度(即子列表的值)来区分它们,然后在椭圆特征与其轴对应,然后绘制一条从特征一端到另一端的线并找到它的距离。由于值错误,我一直坚持将嵌套列表分成坐标。我真的很感激一个新的视角!

shanchuang2006 回答:当我使用 for 循环进行迭代时,有没有办法在嵌套列表中找到子列表的索引?

xcoord = []
ycoord = []

for (ycord,sublist) in enumerate(nested_lst):
    for (xcord,item) in enumerate(sublist):
        if item > 45:
            xcord.append(xcord)
            ycord.append(ycord)
,

y 轴你想要什么如果值那么这将起作用

  xcord = []
  ycord = []
    
  for sublist in nested_lst:
  for (index,item) in enumerate(sublist):
      if item > (45):
          xcord.append(index)
          ycord.append(item)
,

我认为您的错误是因为 item 之一不是浮点数,但鉴于您的nested_lst 的结构,我不明白为什么会这样。您需要提供完整的nested_lst 数组让我知道。

其次,你有一个小错误;您正在尝试附加到 xcord 和 ycord,这应该是 xcoord 和 ycoord。

本文链接:https://www.f2er.com/1093297.html

大家都在问