简体   繁体   中英

How to zip multiple but an unknown number of lists?

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"], .... ) 

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM