-5

I have a list in this way:

list = [1,2,3,4,5,6,7,8,9]

And reorder it like so:

list2 = [[1,4,7],[2,5,8],[3,6,9]]

Basically paring it with list comprehension the first element with the 4th and 7th, the second with 5th and 8th, and the third with the 6ht and 9th, so skipping every two values.

EGM8686
  • 1,492
  • 1
  • 11
  • 22

1 Answers1

1

You may create a list comprehension expression like:

  • if you want to divide the list based on the "count" of bucket:

    >>> bucket_count = 3
    >>> my_list = [1,2,3,4,5,6,7,8,9,10,11,12]
    
    >>> [my_list[i::bucket_count] for i in range(bucket_count)]
    [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
    
  • if you want to divide the list based on the "size" of bucket:

    >>> bucket_size = 3
    >>> bucket_count = len(my_list)/bucket_size  # Calculate bucket count based on size
    
    # Same logic as above
    >>> [my_list[i::bucket_count] for i in range(bucket_count)]
    [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
    
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126