koko-roshi
koko-roshi

Reputation: 1

Is there a way to find the index of a sublist in a nested list while I'm iterating with a for loop?

I have a 2D array where the indices of the sublists are the y-coordinates and the elements in the sublists are the x-coordinates.

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

It's a large array - (2048, 2098) - of floats. I want to plot a scatter plot where the points are the elements that fulfill a condition like if item > 45 for example.

So far I have this:

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))

I run it but it gives me this error message:

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

Not sure if I should mention that the nested list is the data array of a CCD image in a FITS file that I've zoomed into the centre of to focus on an object. The purpose of me making this scatterplot is so I can measure certain features of the image, so I thought to first make a plot of the feature's boundaries since I can differentiate them by their brightness i.e. the sublists' values and then find the points on the elliptic features that correspond to its axes, and then plot a line from one end of the feature to the other and find its distance. I've been stuck on separating the nested list into the coordinates because of the value error. I'd really appreciate a new perspective!

Upvotes: 0

Views: 274

Answers (3)

atrapp
atrapp

Reputation: 31

I think your error is coming from the fact that one of the items is not a float, but I don't see why that would be, given the structure of your nested_lst. You would need to provide the full nested_lst array for me to tell.

Secondly, you have a minor typo; you are trying to append to xcord and ycord, which should be xcoord and ycoord.

Upvotes: 0

Suraj Shejal
Suraj Shejal

Reputation: 650

what yo want in y axis if values then this will work

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

Upvotes: 0

napuzba
napuzba

Reputation: 6288

xcoord = []
ycoord = []

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

Upvotes: 0

Related Questions