Skip to main content
 首页 » 编程设计

python之在 python 中组合列表

2025年05月04日14Terrylee

我正在尝试合并 2 个列表并希望形成组合。

a = ['ibm','dell'] 
b = ['strength','weekness'] 

我想形成像 ['ibm strength','ibm weekness','dell strength','dell weakness'] 这样的组合。

我尝试使用 zip 或连接列表。我也使用了 itertools 但它没有给我想要的输出。请帮忙。

a = ['ibm','dell'] 
b = ['strength','weekness'] 
c = a + b 
itertools.combinations(c,2) 
for a in a: 
    for b in b: 
        print a +b 

请您参考如下方法:

您正在寻找 product() .试试这个:

import itertools 
 
a = ['ibm', 'dell'] 
b = ['strength', 'weakness'] 
 
[' '.join(x) for x in itertools.product(a, b)] 
=> ['ibm strength', 'ibm weakness', 'dell strength', 'dell weakness'] 

要遍历结果,请不要忘记 itertools.product() 返回一个只能使用一次的迭代器。如果您以后需要它,请将其转换为列表(就像我上面所做的那样,使用列表理解)并将结果存储在变量中以备将来使用。例如:

lst = list(itertools.product(a, b)) 
for a, b in lst: 
    print a, b