2014-01-06 39 views
0

拆分蟒蛇名单上有类似的列表:如何用逗号

industries_list = ["Computers, Internet","Photography, Tourism","Motoring, Manufacturing"] 

我怎么可以拆分这个列表中,以便输出会是这样的:

industries_list = [["Computers","Internet"],["Photography","Tourism"],["Motoring","Manufacturing"]] 

我曾尝试把它转换为字符串,用逗号分割它,然后把它放回到列表中,但是这并没有给我想要的结果。

+0

感谢您的答案,大家解答作品':)' – Renier

回答

2

使用列表理解:

>>> industries_list = ["Computers, Internet","Photography, Tourism","Motoring, Manufacturing"] 
>>> [s.split(',') for s in industries_list] 
[['Computers', ' Internet'], ['Photography', ' Tourism'], ['Motoring', ' Manufacturing']] 

而除去白色空间:

>>> from string import strip 
>>> [map(strip, s.split(',')) for s in industries_list] 
[['Computers', 'Internet'], ['Photography', 'Tourism'], ['Motoring', 'Manufacturing']] 

你也可以使用纯列表理解(嵌入列表理解):

>>> [[w.strip() for w in s.split(',')] for s in industries_list] 
[['Computers', 'Internet'], ['Photography', 'Tourism'], ['Motoring', 'Manufacturing']] 
+0

如果你正在使用'图()',你知道它不会在Python 3的正常工作,而且我d使用'map(str.strip,s.split(','))'而不是导入。 –

+0

感谢您的彻底解答 – Renier

1

在列表理解中将每个值拆分','

industries_list = [s.split(',') for s in industries_list] 

您可能要剥去周围的结果多余的空格:

industries_list = [[w.strip() for w in s.split(',')] for s in industries_list] 

演示:

>>> industries_list = ["Computers, Internet","Photography, Tourism","Motoring, Manufacturing"] 
>>> [s.split(',') for s in industries_list] 
[['Computers', ' Internet'], ['Photography', ' Tourism'], ['Motoring', ' Manufacturing']] 
>>> [[w.strip() for w in s.split(',')] for s in industries_list] 
[['Computers', 'Internet'], ['Photography', 'Tourism'], ['Motoring', 'Manufacturing']] 
3

使用.split String类:

>>> industries_list=["Computers, Internet","Photography, Tourism","Motoring, Manufacturing"] 
>>> [var.split(',') for var in industries_list] 
[['Computers', ' Internet'], ['Photography', ' Tourism'], ['Motoring', ' Manufacturing']] 

如果你不想要空格:

>>> [[s.strip() for s in var.split(',')] for var in industries_list] 
[['Computers', 'Internet'], ['Photography', 'Tourism'], ['Motoring', 'Manufacturing']] 

Live demo.