如何按comm拆分python列表

2024-10-06 12:29:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似的清单:

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

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

^{pr2}$

我试着把它转换成字符串,用逗号把它分开,然后放回一个列表中,但这并没有给出我想要的结果。在


Tags: 字符串列表internetlist逗号manufacturingindustriespr2
3条回答

使用列表理解:

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

删除空白:

^{pr2}$

您还可以使用纯列表理解(嵌入式列表理解):

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

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

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

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

^{pr2}$

演示:

>>> 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']]

在string类上使用.split

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

如果您不想占用空间:

^{pr2}$

Live demo.

相关问题 更多 >