Home > Blockchain >  how to extract values from list with different amounts of brackets?
how to extract values from list with different amounts of brackets?

Time:04-10

I have to extract values from a list, but it only works when I have a list with a double bracket (bbox=[[]]), when it has a single bracket (bbox=[]) it gives me this error: cannot unpack non-iterable int object.

#bboxes = [[396, 386, 531, 586], [449, 387, 536, 494]]
bboxes = [396, 386, 531, 586]
instp = []
if not instp:
  instp = bboxes
for i in bboxes:
  x1,y1,x2,y2 = i
  bbox = [x1,y1,x2,y2]
  print("bbox",bbox)

How can I make my code work in both cases?

CodePudding user response:

To extract from single list, you don't need the for-loop. Just write

x1,y1,x2,y2 = bboxes

To make your code work in both cases, you could for example check if the type of the first element in the list is list or int and use the for-loop or simple unpack solution bases on that:

if isinstance(bboxes[0], int):
    x1,y1,x2,y2 = bboxes
else:
    # for-loop etc.
    
  • Related