简体   繁体   中英

Convert Unicode string to nested list

I tried to convert an unicode string like this (that I am getting from a web service):

value = [[u"Seba", u"10"], [u"[Gianfranco", u"80"], [u"[Marco", u"20"], [u"[Massimo", u"125"]] 

And I want to create a nested list in order to be able to sort it via "sorted" method.

This is what I did: First remove all the not needed ""

value = value.replace('"', '')

then strip extra [] and create list with split method:

valuelist = [x.split(',') for x in value.strip('[]').split('],[')]

Finally I am able to sort via sorted method, on second element of the nested list.

valuelist = sorted(valuelist,key=lambda valuelist: int((valuelist[1])), reverse=True)

The code is working but I was wondering if there's a more elegant solution. Thanks

you could try

>>> [[i.encode('ascii', 'ignore').replace('[', '') for i in x] for x in value]
[['Seba', '10'], ['Gianfranco', '80'], ['Marco', '20'], ['Massimo', '125']]

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