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

Time:03-06

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.

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

How might I go about achieving this?

Thanks!

CodePudding user response:

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.

  • Related