crasshopper 发表于 2014-10-30 15:25

字符串转化为数组嵌套字典

比如:
字符串   a:1,a:2,a:3

转化为:
[{'a':1},{'a':2},{'a':3}]

huangxiaohen 发表于 2014-10-30 15:33

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

Linux_manne 发表于 2014-10-30 16:58

l = "a:2, b:1, c:3"
d={}
[ d.fromkeys(k.strip(),k.strip()) for k in l.split(',')]

Hadron74 发表于 2014-10-30 22:40

本帖最后由 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:14

本帖最后由 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}]

Hadron74 发表于 2014-10-31 19:06

回复 5# Buring__


    是\w好,通用性更强。

pitonas 发表于 2014-11-01 12:22

\w好,通用性是更强的。

学习了。
页: [1]
查看完整版本: 字符串转化为数组嵌套字典