nested map() ?

Michael P. Reilly arcege at shore.net
Mon Apr 5 11:58:52 EDT 1999


Randall Hopper <aa8vb at vislab.epa.gov> wrote:
: To generate all permutations of list elements in Perl, it's sometimes
: useful to do this:

:      @result = map { $a = $_ ; map{ "$a$_" } @B } @A

: Is there a relatively short way to do this in Python?

: Thanks,

: Randall

This assumes that you want to take advantage of Perl's flat array
limitation (i.e. putting an array as an element of an existing array
performs a form of a slice).

You can do this with map and reduce, but it's not the simplest, fastest,
shortest method.
  result = reduce(
    lambda a, b: a + b,
    map(
      lambda aitem, b=b: map(
        lambda bitem, aitem=aitem: "%s%s" % (aitem, bitem),
        b
      ), a
    )
  )

This can be done more efficiently with:
  result = []
  for aitem in a:
    for bitem in b:
      result.append( "%s%s" % (aitem, bitem) )

Also, you might want to store `(aitem, bitem)' instead of
`"%s%s" % (aitem, bitem)'.  Unless you _need_ the string concatenation,
storing a tuple of the two objects would make them easier to use later.

  -Arcege





More information about the Python-list mailing list