2017-03-07 53 views
0

假设:如何列表中的每个元素有两个清单合并到其他列表

['a', 'b', 'c'], ['d', 'e', 'f'] 

我要的是:

'ad','ae','af','bd','be','bf','cd','ce','cf' 


first_list = ['a', 'b', 'c'] 
second_list = ['d', 'e', 'f'] 
combined_list = [] 
for i in first_list: 
    for j in second_list: 
     combined_list.append(i + j) 
print(combined_list) 

我的问题是,如果不仅有两份名单,如何改进代码? 例如,

first_list = ['a', 'b', 'c'] 
second_list = ['d', 'e', 'f'] 
third_list = ['g','h','q'] 
print ['adg','adh','adq','aeg','aeh',.......] 

家伙,还有什么可推广的方式来表演n lists..I意思是,如果有什么有超过三个列表?

回答

0

我还没有测试过,但这应该工作。

first_list = ['a', 'b', 'c'] 
second_list = ['d', 'e', 'f'] 
third_list = ['g','h','q'] 
combined_list = [] 
for i in first_list: 
    for j in second_list: 
     for k in third_list: 
      combined_list.append(i + j + k) 
print(combined_list) 
+1

这不能推广到任意数量的列表。该投票不是我的,顺便说一句 – Alexander

+0

是的,它不是通用的...如果有n个列表? –

2

这被称为笛卡尔产品。

import itertools 

first_list = ['a', 'b', 'c'] 
second_list = ['d', 'e', 'f'] 
third_list = ['g','h','q'] 
lists = [first_list, second_list, third_list] 

cartesian_product = [''.join(x) for x in itertools.product(*lists)] 

print(cartesian_product) 

输出:

['adg', 'adh', 'adq', 'aeg', 'aeh', 'aeq', 'afg', 'afh', 'afq', 
'bdg', 'bdh', 'bdq', 'beg', 'beh', 'beq', 'bfg', 'bfh', 'bfq', 
'cdg', 'cdh', 'cdq', 'ceg', 'ceh', 'ceq', 'cfg', 'cfh', 'cfq'] 

你可以在线试用,here

这里是一个笛卡尔生产函数,你可以尝试here的示例实现。

def cartesian_product(*lists): 
    if not lists: # base case 
     return [[]] 
    else: 
     this_list = lists[0] 
     remaining_lists = lists[1:] 
     return [ 
      [x] + p 
      for x in this_list 
       for p in cartesian_product(*remaining_lists) 
     ] 
+0

谢谢!顺便说一句,你知道循环中的任何方式,我的意思是,用于...而不是itertools –

+0

当然,我可以做的实施。给我一些时间。 – Alexander

+0

@Lindadadad我会用一个生成器表达式来简化这个,但是如果你愿意,你可以将它转换为for循环 – Alexander

相关问题