简体   繁体   中英

How do I reverse the effects of str() Method in Python?

I am wondering if python has an in-build method to reverse the str() method.

Example: MyList contains a dictionary, a string and an integer.

MyList = [{1: 'one'}, 'blarg', 964]

Let's say i want to arrange these items in order of size(length). here is my function

def sort_by_length(mylist):
    newlist = []
    final = []
    for i in mylist:
        newlist.append(str(i))
    final = list(reversed(sorted(newlist, key=len)))
    for n,i in enumerate(final):
        if i.isdigit() == True:
            final[n]=int(i)
        else:
            pass
    return final

If I run this Function on MyList

sort_by_length(MyList)

The current output is:

["{1: 'one'}", 'blarg', 964]

Expected output:

[{'1': 'one'}, 'blarg', 964]

I was able to change the Integer back from a string but the dictionary remains a string in Quotation Marks(obviously because i only reversed the str() only for the Integers and not the dictionaries).

How would I be able to reverse this element back to a Dictionary?

You need to use the key parameter to sorted to specify a function to be called. Here a lambda expression will work fine.

>>> MyList = [{1: 'one'}, 'blarg', 964]
>>> sorted(MyList, key=lambda x: len(str(x)), reverse=True)
[{1: 'one'}, 'blarg', 964]

Generally str() is not meant to give something that you can decode back into a python object. It is meant to give a human readable string. If you want to encode into a string that is machine readable use something like json .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM