An ordering question

John Posner jjposner at
Fri Mar 13 21:43:03 CET 2009

> If you don't want to build the intermediary dict, a
> less efficient
> version that runs in O(n^2):
> a.sort(key=lambda k: b.index(k[1]))
> Which is mostly similar to John's solution, but still
> more efficient
> because it only does a b.index call once per 'a'
> item instead of twice
> per comparison.

Very nice! This solution is pretty much a direct transliteration of the original problem, as the OP *might* have articulated it:

  List A consists of ordered pairs. Sort list A according to the
  position in list B of the pair's second member.

A solution is truly "Pythonic" when it possesses this directness.


More information about the Python-list mailing list