a better way to invert a list?

Peter Otten __peter__ at web.de
Wed Apr 6 05:58:35 EDT 2011


Glazner wrote:
>> > def invert(p):
>> > inverse = [None] * len(p)
>> > for (i, j) in enumerate(p):
>> > inverse[j] = i
>> > return inverse
>>>> Elegant. This seems like the best solution, although it isn't as much
>> fun to write as a "one-liner". Thanks
>>>>>> invert([1, 2, 3, 1])
> [None, 3, 1, 2] #blah

1 occurs twice in [1, 2, 3, 1] which therefore doesn't describe a 
permutation. In general a function has to be "bijective" to be invertable. 
You can catch the problem with (untested)
def invert(p):
 inverse = [None] * len(p)
 for i, k in enumerate(p):
 if inverse[k] is not None:
 raise ValueError
 inverse[k] = i
 return inverse


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /