Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #11719

Re: pairwise combination of two lists

From Marc Christiansen <usenet@solar-empire.de>
Newsgroups comp.lang.python
Subject Re: pairwise combination of two lists
Date 2011-08-17 23:43 +0200
Message-ID <g9pth8-7co.ln1@pluto.solar-empire.de> (permalink)
References <mailman.146.1313614713.27778.python-list@python.org>

Show all headers | View raw


Yingjie Lin <Yingjie.Lin@mssm.edu> wrote:
> Hi Python users,
> 
> 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.

Depending on your needs, we can offer you three solutions:

For our customers who want it all at once, but without any unneccessary
waste, the list expression:
[a + b for a, b in itertools.product(li1, li2)]

or if you don't need the whole list at once (especially interesting for
our customers with large lists), the generator expression (genexp):
(a + b for a, b in itertools.product(li1, li2))

and if you don't like the throwaway genexp and want something more
ecofriedly, we can present you a memory efficient, reusable solution, the
generator:
def combiner(li1, li2):
    for a, b in itertools.product(li1, li2):
        yield a + b

;)

HTH, Marc

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

pairwise combination of two lists Yingjie Lin <Yingjie.Lin@mssm.edu> - 2011-08-17 16:22 -0400
  Re: pairwise combination of two lists Mel <mwilson@the-wire.com> - 2011-08-17 17:15 -0400
    Re: pairwise combination of two lists Mel <mwilson@the-wire.com> - 2011-08-17 17:18 -0400
  Re: pairwise combination of two lists Marc Christiansen <usenet@solar-empire.de> - 2011-08-17 23:43 +0200
  Re: pairwise combination of two lists Luis M. González <luismgz@gmail.com> - 2011-08-17 16:27 -0700
  Re: pairwise combination of two lists Paul Rubin <no.email@nospam.invalid> - 2011-08-18 00:18 -0700
  Re: pairwise combination of two lists Alain Ketterlin <alain@dpt-info.u-strasbg.fr> - 2011-08-18 09:30 +0200
  Re: pairwise combination of two lists SigmundV <sigmundv@gmail.com> - 2011-08-18 14:51 -0700

csiph-web