0

My code:

import random
randomlist = []
result_list=[]
l=int(input('Enter List Length'))
for i in range(0,l):
    n = random.randint(1,30)
    randomlist.append(n)
print(randomlist)
n=int(input('composite range:'))
composite_list = [randomlist[x:x + n] for x in range(0, len(randomlist), n)]
print(composite_list)
# zip inner list
for i in composite_list:
    #stucked here

I wish to zip all list elements to a new list for example:
Random List: [25, 6, 15, 7, 21, 30, 10, 14, 3]
composite_list:[[25, 6, 15], [7, 21, 30], [10, 14, 3]]
Output list after zip: [[25, 7, 10],[6, 21, 14],[15, 30, 3]]
Because number of elements in composite_list is randomly. I have no idea how to use zip()

rdas
  • 20,604
  • 6
  • 33
  • 46
holaling
  • 25
  • 1
  • 5

3 Answers3

0

You can do the following:

rand_lst = [25, 6, 15, 7, 21, 30, 10, 14, 3]

it = iter(rand_lst)
comp_lst = list(zip(it, it, it))
# [(25, 6, 15), (7, 21, 30), (10, 14, 3)]

trans_lst = list(zip(*comp_lst))
# [(25, 7, 10), (6, 21, 14), (15, 30, 3)]

This uses the old "zip iterator with itself" pattern to create the chunks. Then you can zip the chunks by unpacking the list using the * operator. This also works in a single step:

it = iter(rand_lst)
trans_lst = list(zip(*zip(it, it, it)))
user2390182
  • 72,016
  • 6
  • 67
  • 89
0

Use:

list(zip(*composite_list))
# output is a list of tuples

Or:

list(map(list, zip(*composite_list)))
# output is a list of lists

to look exactly your desired output.

Austin
  • 25,759
  • 4
  • 25
  • 48
0

Using numpy:

import numpy as np

np.array(composite_list).T.tolist()

Outputs:

[[25, 7, 10], [6, 21, 14], [15, 30, 3]]

Caveat would be probably even better, if you would keep your whole flow in numpy, otherwise converting to numpy might be a bit of a overhead.

Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34