如何用逗号分割python列表

时间:2014-01-06 08:05:31

标签: python list

我的列表类似于:

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

如何拆分此列表,以便输出类似于:

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

我尝试将其转换为字符串,用逗号分隔,然后将其放回列表中,但这并没有给出我想要的结果。

3 个答案:

答案 0 :(得分:3)

在字符串类上使用.split

>>> 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.

答案 1 :(得分: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']]

答案 2 :(得分: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']]
相关问题