简体   繁体   中英

How do you create Tuples from two lists so that one list elements repeat

I'm trying to join 2 list such that the values in the first list get joined to the values in the second list in order and then join again when the list one items have exhausted...

worker_tables=['table1','table2']

mylist = [['val1','val2'], ['val3','val4'],['val5','val6'],['val7','val8'],['val9','val10']]

mylist_tup = zip(mylist, worker_tables)

the result i'm getting is--

print mylist_tup

[(['val1', 'val2'], 'table1'), (['val3', 'val4'], 'table2')] 

as you see, it's not joining back to table1 and table2 fields from the first list..

desired output=

 [(['val1', 'val2'], 'table1'),(['val3', 'val4'], 'table2'), (['val5', 'val6'], 'table1'),(['val7', 'val8'], 'table2'), (['val9', 'val10'], 'table1')]

You can use itertools.cycle to achieve the desired result:

from itertools import cycle

mylist_tup = zip(mylist, cycle(worker_tables))

This will cycle through the values of worker_tables as many times as needed.

You can repeat the worker_table list items out to the length of mylist:

worker_tables=['table1','table2']

mylist = [['val1','val2'], ['val3','val4'],['val5','val6'],['val7','val8'],['val9','val10']]

mylist_tup = zip(mylist, worker_tables * int(len(mylist) / len(worker_tables)))

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