a better way to invert a list?

scattered tooscattered at gmail.com
Tue Apr 5 17:17:33 EDT 2011


Greetings,

I've been playing around (in Python 3.1) with permutations of
0,1,...,n-1, represented by lists, p, of length n, where p[i] = the
image of i under the permutation. I wanted to be able to calculate the
inverse of such a permutation, and came up with the following succint
but not quite readable function:

def invert(p):
	return [ j for (i,j) in sorted(zip(p,range(len(p))))]

I rejected the obvious [p.index(i) for i in range(len(p))] since that
seems an inefficient way to sort. Is there a better way to do this?

Another question about my code: What is more idiomatic, [ j for (i,j)
in ...]   or [ x[1] for x in ... ]? I find the former more readable.
But it makes bindings for i and doesn't use them - which can't be very
efficient. In Haskell or ML, you can use patterns that contain wild
cards that play a role in the pattern-matching but don't establish any
binding. Can that be done in Python?

Thanks





More information about the Python-list mailing list