开发者

Parse a map of int -> list from a string

开发者 https://www.devze.com 2023-01-20 10:15 出处:网络
This should be a fairly straight forward python question, but I\'m getting stuck getting the syntax right.

This should be a fairly straight forward python question, but I'm getting stuck getting the syntax right.

Let's say I have a string:

"1:a,b,c::2:e,f,g::3:h,i,j"

and I want to convert this to a map like so:

{'1': ['a', 'b', 'c'], '2': ['e', 'f', 'g'], '3': ['h', 'i', 'j']}

How would this be done?

I can figure out how to do it using nested for loops, but would be cool to just do it in a s开发者_Python百科ingle line.

Thanks!


Here's one approach:

dict((k, v.split(',')) for k,v in (x.split(':') for x in s.split('::')))
0

精彩评论

暂无评论...
验证码 换一张
取 消