我正在尝试合并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