user8652079
user8652079

Reputation: 55

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

Upvotes: 0

Views: 59

Answers (2)

Apollo2020
Apollo2020

Reputation: 519

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

Upvotes: 1

Tom Karzes
Tom Karzes

Reputation: 24052

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.

Upvotes: 5

Related Questions