我有一个类似的列表:
industries_list = ["Computers, Internet","Photography, Tourism","Motoring, Manufacturing"]
我怎样才能拆分这个列表,以便输出类似于:
industries_list = [["Computers","Internet"],["Photography","Tourism"],["Motoring","Manufacturing"]]
我试过将它转换为字符串,用逗号分隔,然后将它放回列表中,但这并没有给我想要的结果。
请您参考如下方法:
使用列表理解:
>>> 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']]
