[英]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]
['a','b','c','d']
和[1,1,2,3]
is there any pythonic way of doing this without using eval (it doesnt work anyways)? 是否有任何不使用eval的方式来执行此操作的Python方法(反正还是不起作用)?
You can use re.findall()
to find the characters and numbers and zip
function to separate them : 您可以使用re.findall()
查找字符和数字,并使用zip
函数将它们分开:
>>> 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)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.