Home > Mobile >  how do I extract the elements with the same value in a list
how do I extract the elements with the same value in a list

Time:07-15

I have a group of data in the format of:

log = [[timestamp, x_coordinate, y_coordinate]]

which looks something like:

log = [[500, 20, 20], [500, 25, 25], [500, 22, 25], [1000, 20, 25], [1000, 30, 25]...]

There is quite a lot of data so I want to process them faster. Is there a way to process the data with the same timestamp altogether and then move on to the next timestamp?

So far I have tried to use for loop to do the favor, but it still works very slow. Is there another way to process the data faster?

for item in log:
     if item[0] == ts:
          draw_tracking(output_img, item[1], item[2])

Desired output is a bit complicated. I want to draw a box based on the data from the list. I have this function:

def draw_tracking(img, x, y):
    pt_1 = (x, y)
    pt_2 = ((x 5), (y 5))
    cv2.rectangle(img, pt1=pt_1, pt2=pt_2, color=(255,0,0), thickness=5)
    plt.imshow(img)

CodePudding user response:

You can do a pre process first, something like this:

from collections import defaultdict

grouped = defaultdict(list)

for item in log:
    grouped[item[0]] = (item[1], item[2])

Now, when you want to draw a timestamp (ts), you can do:

for item in grouped[ts]:
    draw_tracking(output_img, item[0], item[1])

This way you only iterate over the full list onece, for the preprocess, then, for each timestamp, you only iterate over that timestamp "entries".

CodePudding user response:

if you wanna to find out the data of a given timestamp, the fllowing code may works:

[{'timestamp': _[0], 'data': _} for _ in log if _[0] == YOUR_TIMESTAMP ]

if you wanna to group the data by timestamp, you may consider the code bellow

{_[0]: [__ for __ in log if __[0]==_[0]]  for _ in log}
  • Related