我正在尝试合并2个列表,并希望形成组合.
a = ['ibm','dell']
b = ['strength','weekness']
我想形成一些组合,例如[‘ibm优势’,’ibm每周’,’dell优势’,’dell劣势’].
我尝试使用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