Skip to main content
 首页 » 编程设计

python之如何在python中连接多个数组

2025年05月04日15落叶

我有 4 个这样的数组:

temp1 = ['a' , 'b' , 'c'] 
temp2 = ['d' , 'e' ,'' ] 
temp3 = ['f'] 
temp4 = ['g'] 

我想要输出:

adfg 
aefg 
afg 
bdfg 
befg 
bfg 
cdfg 
cefg 
cfg 

我用下面的方法解决了它:

temp1 = ['a' , 'b' , 'c'] 
temp2 = ['d' , 'e' ,'' ] 
temp3 = ['f'] 
temp4 = ['g'] 
for list_1 in temp1: 
    for list_2 in temp2: 
        for list_3 in temp3: 
            for list_4 in temp4: 
                temp_list = '' 
                if list_1: temp_list += list_1 
                if list_2: temp_list += list_2 
                if list_3: temp_list += list_3 
                if list_4: temp_list += list_4 
                print "%s " %(temp_list) 

但我认为我的代码效率不高。

如何制定好的算法并使其高效。

如果 temp3 为 null 例如:

temp1 = ['a' , 'b' , 'c'] 
temp2 = ['d' , 'e' ,'' ] 
temp3 = [] 
temp4 = ['g'] 

请您参考如下方法:

您可以使用 itertools.product :

>>> from itertools import product 
>>> result = product(temp1, temp2, temp3, temp4) 
>>> ["".join(item) for item in result] 
['adfg', 'aefg', 'afg', 'bdfg', 'befg', 'bfg', 'cdfg', 'cefg', 'cfg'] 

更新:

如果 temp3 在更新后的问题中是空的,我想你会想在生成结果时跳过它。如果是这种情况,您只能使用包含某些项目的列表:

>>> input_lists = [arr for arr in (temp1, temp2, temp3, temp4) if arr] 
>>> result = product(*input_lists) 
>>> ["".join(item) for item in result] 
['adg', 'aeg', 'ag', 'bdg', 'beg', 'bg', 'cdg', 'ceg', 'cg']