【问题标题】:split a string with commas inside of a list python [closed]在列表python中用逗号分割字符串[关闭]
【发布时间】:2023-03-27 06:35:01
【问题描述】:

我有这份清单

l = [[hello,world],[i need help, python]] 
l [0] = [hello, world] 
l [1] = [i need help, python]

我需要用逗号分隔l[0]l[1],但我不知道该怎么做 因为"hello, world""i need help, python" 是字符串。

谁能帮帮我!

【问题讨论】:

  • 目前它们不是字符串。你能至少包括引号吗?预期的输出是什么?

标签: python list split


【解决方案1】:

这是我用于解决此类问题的递归方法...

def explode(sep,x):
    if isinstance(x,(str,unicode)): return x.split(sep)
    elif isinstance(x,list): return [explode(sep,each) for each in x]
    elif isinstance(x,dict):return {key:explode(sep,x[key]) for key in x}
    else: raise ValueError("function doesn't support",type(x))

l = [["hello,world"],["i need help, python"]] 
l = explode(",",l)

【讨论】:

    【解决方案2】:

    只需遍历列表并使用 myString.split(",") 拆分每个条目

    【讨论】:

    • 然后呢? OP 没有明确指定拆分的结果应该去哪里..
    • 他有分裂的问题,我想他知道如何处理之后的结果。
    【解决方案3】:

    我想你想循环遍历列表:

    >>> l = [['hello,world'],['i need help, python']] 
    >>> for x in l:
    ...     print x[0]       # if you sung python 3x print(x[0])
    ... 
    hello,world
    i need help, python
    

    如果要拆分字符串:

    >>> for x in l:
    ...     print x[0].split(',')
    ... 
    ['hello', 'world']
    ['i need help', ' python']
    

    阅读split

    【讨论】:

    • 然后他可以添加split x[0].split()
    • 然后呢?是否应该更改原始列表?存储在一个新的平面列表中?缺少太多细节。
    • 为什么有人投反对票???
    • 我做了,因为您最初的编辑未能解决问题。
    • OP 不清楚,所以我涵盖了所有方面:)
    猜你喜欢
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多