Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I group a 2 dimensional list of objects in python 3.10?

I have a list of gifs. Each "gif" is a list of frame objects setup like this.

gifs = [ [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], ...]

I need to order them is to a list of lists where each sub-list contains the nth corresponding frame. i.e.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

orderedGifs = [ [1, 1, 1, ...], [2, 2, 2, ...], [3, 3, 3, ...], ...]

How might I go about achieving this?

Thanks!

>Solution :

As @enke indicates in the comments, using list(zip(*gifs)) gets you the transposition – but it will be a list of tuples.

If you need the groups to be lists, this works:

orderedGifs = list(map(list, zip(*gifs)))

It works because:

  • *gifs unpacks the original gifs and passed all its contents to zip() (spreading)
  • zip() pairs up elements in tuples from each iterable it’s passed, in your case the 1st element of each list, then the 2nd, etc.
  • map(list, xs) takes each element from xs and applies list() to it, returning an iterable of the results

So wrapping the whole thing in list() takes the tuples converted to lists and puts them in a list, as required.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading