Apr 5, 1999, 8:58 AM
Post #2 of 2
(1383 views)
Permalink
Randall Hopper <aa8vb@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