简体   繁体   中英

stringified list to two separate lists

I have a stringified list that looks something like this:

'[a:1,b:1,c:2,a:3]'

I want to separate this into two lists.

['a','b','c','d'] and [1,1,2,3]

is there any pythonic way of doing this without using eval (it doesnt work anyways)?

You can use re.findall() to find the characters and numbers and zip function to separate them :

>>> a='[a:1,b:1,c:2,a:3]'

>>> import re
>>> zip(*re.findall(r'([a-z]):(\d)',a))
[('a', 'b', 'c', 'a'), ('1', '1', '2', '3')]
import re
zip(*re.findall(r'([a-z]):([0-9])', my_string))

Depending your use, you can also add some + :

>>> zip(*re.findall(r'([a-z]+):([0-9]+)', '[a:1,blabla:1,c:20,a:3]'))
[('a', 'blabla', 'c', 'a'), ('1', '1', '20', '3')]

Just to go a little bit further in the requirement to get a list of ints:

str = '[a:1,b:1,c:2,a:3]'
p,q = zip(*[(x,int(y)) for x,y in re.findall('([a-z]+):(\d+)', str)])

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