[Tutor] unstring
Steven D'Aprano
steve at pearwood.info
Wed Jun 19 07:58:29 CEST 2013
On Tue, Jun 18, 2013 at 10:34:23PM -0700, Jim Mooney wrote:
> On 18 June 2013 19:41, Steven D'Aprano <steve at pearwood.info> wrote:
> > On Tue, Jun 18, 2013 at 06:41:01PM -0700, Jim Mooney wrote:
> >> Is there a way to unstring something? That is str(object) will give me
> >> a string, but what if I want the original object back, for some
> >> purpose, without a lot of foofaraw?
> >
> > The short answer is, "no".
>
> It just occurred to me that a sort key can sort by changing the input
> to return a string, but the actual list member is not changed to a
> string, so maybe there's a fudge there.
Nope, sorting with a key function uses the "DSU" (Decorate Sort
Undecorate) idiom. Up until a few versions back (2.3 or 2.4, I think),
you used to have to do this by hand:
# sort numbers in dictionary order, not numeric
L = list(range(25))
L = [(str(item), item) for item in L] # decorate
L.sort()
L = [t[1] for t in L] # undecorate
print(L)
Python's sort now does this for you:
L.sort(key=str)
sorted(L, key=str)
but the way it's done under the hood is pretty much identical.
--
Steven
More information about the Tutor
mailing list