将字符串拆分为元组列表

Law*_*nce 2 python

如果我有一个像这样的字符串:

"user1:type1,user2:type2,user3:type3" 
Run Code Online (Sandbox Code Playgroud)

我想将其转换为元组列表,如下所示:

[('user1','type1'),('user2','type2'),('user3','type3')]
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?我是python的新手,但在文档中找不到一个很好的例子来做到这一点.

谢谢!

Fog*_*ird 11

>>> s = "user1:type1,user2:type2,user3:type3"
>>> [tuple(x.split(':')) for x in s.split(',')]
[('user1', 'type1'), ('user2', 'type2'), ('user3', 'type3')]
Run Code Online (Sandbox Code Playgroud)


Cla*_*diu 5

最干净的方法是使用列表理解进行两次分割:

str = "user1:type1,user2:type2,user3:type3"
res = [tuple(x.split(":")) for x in str.split(",")]
Run Code Online (Sandbox Code Playgroud)