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


Groups > comp.lang.python > #2673

a better way to invert a list?

From scattered <tooscattered@gmail.com>
Newsgroups comp.lang.python
Subject a better way to invert a list?
Date 2011-04-05 14:17 -0700
Organization http://groups.google.com
Message-ID <2215eefd-3677-4459-8656-aa04978f6f3f@g7g2000pro.googlegroups.com> (permalink)

Show all headers | View raw


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

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


Thread

a better way to invert a list? scattered <tooscattered@gmail.com> - 2011-04-05 14:17 -0700
  Re: a better way to invert a list? Ian Kelly <ian.g.kelly@gmail.com> - 2011-04-05 15:46 -0600
    Re: a better way to invert a list? scattered <tooscattered@gmail.com> - 2011-04-05 16:24 -0700
      Re: a better way to invert a list? Glazner <yoavglazner@gmail.com> - 2011-04-06 01:48 -0700
        Re: a better way to invert a list? scattered <tooscattered@gmail.com> - 2011-04-06 02:48 -0700
        Re: a better way to invert a list? Peter Otten <__peter__@web.de> - 2011-04-06 11:58 +0200
    Re: a better way to invert a list? Raymond Hettinger <python@rcn.com> - 2011-04-05 17:07 -0700
  Re: a better way to invert a list? Paul Rubin <no.email@nospam.invalid> - 2011-04-06 12:51 -0700
    Re: a better way to invert a list? Ian Kelly <ian.g.kelly@gmail.com> - 2011-04-06 14:08 -0600

csiph-web