Combining lists in python

风流意气都作罢 提交于 2019-12-19 10:44:06

问题


I am trying to combine 2 lists and want to form combinations.

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

I want to form combinations like ['ibm strength','ibm weekness','dell strength','dell weakness'].

I tried to use zip or concatenated the lists. I also used itertools but it doesn't give me desired output. Please help.

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

回答1:


You're looking for product(). Try this:

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']

To loop over the results don't forget that itertools.product() returns an iterator that can be consumed only once. If you need it at a later time, convert it into a list (as I did above, using a list comprehension) and store the result in a variable, for future use. For example:

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



回答2:


For a Cartesian product, you want itertools.product() instead of combinations.

A nested for-loop would also work:

for x in a:
    for y in b:
        c = a + b
        print(c)


来源:https://stackoverflow.com/questions/24852992/combining-lists-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!