Python将字符串转换为数组赋值 [英] Python convert string to array assignment
问题描述
在我的应用程序中,我收到一个字符串'abc [0] = 123'
In my application I am receiving a string 'abc[0]=123'
我想将此字符串转换为项目数组.我已经尝试过 eval()
对我不起作用.我知道数组名称 abc
,但是每次的项数都会不同.
I want to convert this string to an array of items. I have tried eval()
it didnt work for me. I know the array name abc
but the number of items will be different in each time.
我可以分割字符串,获取数组索引并执行.但是我想知道是否有任何直接方法可以将此字符串转换为数组插入.我非常感谢任何建议.
I can split the string, get array index and do. But I would like to know if there is any direct way to convert this string as an array insert. I would greately appreciate any suggestion.
推荐答案
这是一个根据php规则解析网址的函数(即使用方括号创建数组或嵌套结构):
Here's a function for parsing urls according to php rules (i.e. using square brackets to create arrays or nested structures):
import urlparse, re
def parse_qs_as_php(qs):
def sint(x):
try:
return int(x)
except ValueError:
return x
def nested(rest, base, val):
curr, rest = base, re.findall(r'\[(.*?)\]', rest)
while rest:
curr = curr.setdefault(
sint(rest.pop(0) or len(curr)),
{} if rest else val)
return base
def dtol(d):
if not hasattr(d, 'items'):
return d
if sorted(d) == range(len(d)):
return [d[x] for x in range(len(d))]
return {k:dtol(v) for k, v in d.items()}
r = {}
for key, val in urlparse.parse_qsl(qs):
id, rest = re.match(r'^(\w+)(.*)$', key).groups()
r[id] = nested(rest, r.get(id, {}), val) if rest else val
return dtol(r)
示例:
qs = 'one=1&abc[0]=123&abc[1]=345&foo[bar][baz]=555'
print parse_qs_as_php(qs)
# {'abc': ['123', '345'], 'foo': {'bar': {'baz': '555'}}, 'one': '1'}
这篇关于Python将字符串转换为数组赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!