[英]Python - Parse a string and convert it into list
I've a string 我有一个字符串
a = "sequence=1,2,3,4&counter=3,4,5,6"
How do I convert it into a list,ie 如何将其转换为列表,即
sequence = [1,2,3,4]
counter = [3,4,5,6]
Use urlparse.parse_qs
( urllib.parse.parse_qs
in Python 3.x) to parse query string: 使用
urlparse.parse_qs
(Python 3.x中的urllib.parse.parse_qs
)来解析查询字符串:
>>> import urlparse
>>> a = "sequence=1,2,3,4&counter=3,4,5,6"
>>> {key: [int(x) for x in value[0].split(',')]
... for key, value in urlparse.parse_qs(a).items()}
{'counter': [3, 4, 5, 6], 'sequence': [1, 2, 3, 4]}
import re
items = "sequence=1,2,3,4&counter=3,4,5,6".split('&')
pattern = re.compile(r'\d+')
for i in items:
print [int(i) for i in re.findall(pattern, i)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.