pairwise combination of two lists
Alain Ketterlin
alain at dpt-info.u-strasbg.fr
Thu Aug 18 03:30:43 EDT 2011
Yingjie Lin <Yingjie.Lin at mssm.edu> writes:
> I have two lists:
>
> li1 = ['a', 'b']
> li2 = ['1', '2']
>
> and I wish to obtain a list like this
>
> li3 = ['a1', 'a2', 'b1', 'b2']
>
> Is there a handy and efficient function to do this, especially when
> li1 and li2 are long lists.
It's not difficult to write your own:
def product(l1,l2):
for x1 in l1:
for x2 in l2:
yield x1+x2
use it like: for p in product(l1,l2) ... The call to product() produces
a generator, the cross product is never built in full, it should work on
long lists.
-- Alain.
More information about the Python-list
mailing list