字符串转化为数组嵌套字典
比如:字符串 a:1,a:2,a:3
转化为:
[{'a':1},{'a':2},{'a':3}]
? l = "a:2, b:1, c:3"
itemDic = {}
itemList = []
p = l.split(",")
for i in p:
p = i.split(":")
itemDic] = int(p)
itemList.append(itemDic)
itemDic = {}
print itemList l = "a:2, b:1, c:3"
d={}
[ d.fromkeys(k.strip(),k.strip()) for k in l.split(',')] 本帖最后由 Hadron74 于 2014-10-30 22:44 编辑
回复 1# crasshopper
回复 3# Linux_manne
还是用正则的findall和字典的解析式吧l = "a:2, b:1, c:3"
import re
z = [{k:int(v)} for k,v in re.findall("(\S+):(\d+)",l)]
print z
结果:
[{'a': 2}, {'b': 1}, {'c': 3}]
本帖最后由 Buring__ 于 2014-10-31 15:23 编辑
回复 4# Hadron74
我这里测试的把\S 换成 \w 是正常的>>> [{k:int(v)} for k,v in re.findall("(\w+):(\d+)",l)]
[{'a': 1}, {'a': 2}, {'a': 3}]
>>> [{k:int(v)} for k,v in re.findall("(\S+):(\d+)",l)]
[{'a:1,a:2,a': 3}] 回复 5# Buring__
是\w好,通用性更强。 \w好,通用性是更强的。
学习了。
页:
[1]