6

我在表格中有字符串

[3339:1.6101369,1062:1.5,5751:1.5,6376:1.5,  ...  ]

我想遍历逗号分隔的键值对。最好或最短的方法是什么?

4

2 回答 2

10
s = "[3339:1.6101369,1062:1.5,5751:1.5,6376:1.5]"
s = s.strip("[]")    # Drop the brackets
for kv in s.split(","):
    key, value = kv.split(":")
    print key, value

或者,您可以将其转换为字典(去掉括号后):

d = dict(kv.split(":") for kv in s.split(","))

然后遍历字典:

for key in d:
    print key, d[key]
于 2011-02-14T22:22:36.170 回答
4
d = ast.literal_eval('{' + s[1:-1] + '}')
于 2011-02-14T22:23:10.530 回答