的列表。如果我有这样的字符串:将一个字符串分解成元组
"user1:type1,user2:type2,user3:type3"
,我想将其转换为元组的列表,像这样:
[('user1','type1'),('user2','type2'),('user3','type3')]
我怎么会去关于这样做?我对python相当陌生,但在文档中找不到一个很好的示例来执行此操作。
谢谢!
的列表。如果我有这样的字符串:将一个字符串分解成元组
"user1:type1,user2:type2,user3:type3"
,我想将其转换为元组的列表,像这样:
[('user1','type1'),('user2','type2'),('user3','type3')]
我怎么会去关于这样做?我对python相当陌生,但在文档中找不到一个很好的示例来执行此操作。
谢谢!
使用split
函数两次。
试试这个为例:
s = "user1:type1,user2:type2,user3:type3"
print [i.split(':') for i in s.split(',')]
-1有几个原因 1)不要使用'str'作为变量名称 2)这不起作用,因为第一个'split'的结果是列表 – 2010-05-25 20:36:11
是的。在编辑中更正。 – 2010-05-25 20:37:24
不要使用'list'作为变量名。 – 2010-05-25 20:39:00
>>> s = "user1:type1,user2:type2,user3:type3"
>>> [tuple(x.split(':')) for x in s.split(',')]
[('user1', 'type1'), ('user2', 'type2'), ('user3', 'type3')]
完美,谢谢! – Lawrence 2010-05-25 20:35:27
请记住接受答案! (勾选它) – 2010-05-26 03:38:28
最彻底的方法是两个裂口与列表理解:
str = "user1:type1,user2:type2,user3:type3"
res = [tuple(x.split(":")) for x in str.split(",")]
>>> s = "user1:type1,user2:type2,user3:type3"
>>> l = [tuple(user.split(":")) for user in s.split(",")]
>>> l
[('user1', 'type1'), ('user2', 'type2'), ('user3', 'type3')]
>>>
:)
如果你想要做到没有for循环,你可以使用map和lambda:
map(lambda x: tuple(x.split(":")), yourString.split(","))
这很有趣,所有三个答案如何完全相同:) – Felix 2010-05-25 20:37:10
@felix“应该有one--和最好只有一个--obvious办法做到这一点。” - py – 2010-05-25 20:39:27
** @ Jweede:**我认为**显而易见**是关键词。有**总是至少有两种**方式做某事:)。 **劳伦斯:**我看到你是新来堆栈**溢出**。您必须通过点击答案左侧的复选标记,在答案的“分数”下面,接受其中一个答案。 – Felix 2010-05-25 21:06:32