Combining lists in python

前端 未结 2 1191
陌清茗
陌清茗 2021-01-16 07:28

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

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

I want to form combina

2条回答
  •  暖寄归人
    2021-01-16 08:00

    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
    

提交回复
热议问题