简体   繁体   English

如何从两个列表创建元组,以便重复一个列表元素

[英]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... 我正在尝试加入2个列表,以使第一个列表中的值按顺序加入第二个列表中的值,然后在列表中的一个项目用尽时再次加入...

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.. 如您所见,它并没有从第一个列表重新加入table1和table2字段。

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: 您可以使用itertools.cycle获得所需的结果:

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. 这将根据需要多次worker_tables的值。

You can repeat the worker_table list items out to the length of mylist: 您可以将worker_table列表项重复到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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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