2
\$\begingroup\$

I want to combine elements in different lists. For example, here are 3 lists.

list_a : [ 1,2,3 ]
list_b : [ 4,5,6 ]
list_c : [ 7,8 ]

Selecting elements from list_b and list_c is mutually exclusive. When including an element from list_b, I'd like to also include an element from list_bb; when including an element from list_c, I'd like to also include an element from list_cc.

list_bb : [ 14,15,16 ]
list_cc : [ 17,18 ]

I wrote this code:

global sum_list=[]
for a in list_a:
    for b in list_b:
        for bb in list_bb:
            sum_list.append([a,b,bb])
for a in list_a:
    for c in list_c:
        for cc in list_cc:
           sum_list.append([a,c,cc])

Is there any better way to get the same result?

\$\endgroup\$
2
\$\begingroup\$

The itertools library has a function called product. You can rewrite your snippet as:

global sum_list=itertools.product(list_a, list_b, list_bb) + itertools.product(list_a, list_c, list_cc)

If you don't want to use itertools (e.g. because you're stuck on python 2.4), you can also use a list comprehension:

global sum_list=[]
sum_list.extend([a,b,bb] for a in list_a for b in list_b for bb in list_bb)
sum_list.extend([a,c,cc] for a in list_a for c in list_c for cc in list_cc)
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.