gpt4 book ai didi

python - 如何用逗号分割 python 列表

转载 作者:太空宇宙 更新时间:2023-11-04 07:41:04 25 4
gpt4 key购买 nike

我有一个类似的列表:

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

关于python - 如何用逗号分割 python 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20945565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com