Home > database >  How to zip multiple but an unknown number of lists?
How to zip multiple but an unknown number of lists?

Time:04-26

I have multiple lists and I want to zip them like shown in the following example :

d = {}
clients = ["client_1","client_2","client_3",...] # n number of client

# every client has a list of element :
d["acc_list"   client] = [1, 2, 3, ...] 

So how could I zip them without knowing the number of clients :

acc_clients = zip(d["acc_list"   "client_0"],d["acc_list"   "client_2"],d["acc_list"   "client_3"], .... ) 

CodePudding user response:

So you already have the client part in client_names, so you can make a list of them:

client_d = [d["acc_list"   client ] for client in client_names]

Now to zip them together you can apply to * operator to the list:

acc_clients = zip(*[d["acc_list"   client ] for client in client_names])

or as @wwii points out, we don't need to get a list comprehension to iterate over client_names first and then let * iterate over the result, we can make a generator expression:

acc_clients = zip(*(d["acc_list"   client ] for client in client_names))
  • Related