给定一个str作为key1:val1,val2,val3,key2:val11,val22
,分割字符串的最有效方法是:
key1: ['val1', 'val2', 'val3']
key2: ['val11', 'val22']
谢谢
答案 0 :(得分:1)
In [150]: answer = {}
In [151]: s = "key1:val1,val2,val3,key2:val11,val22"
In [152]: for pair in s.split(','):
k, _, v = pair.rpartition(":")
if k: key = k
if key not in answer: answer[key] = []
answer[key].append(v)
.....:
In [153]: for k,vals in answer.items():
print(k, ":", vals)
.....:
key2 : ['val11', 'val22']
key1 : ['val1', 'val2', 'val3']