【问题标题】:how to convert a string with comma separated values within a list in python?如何在python的列表中转换带有逗号分隔值的字符串?
【发布时间】:2022-01-21 20:03:02
【问题描述】:

您好,我对 python 比较陌生,并没有完全解决上述问题

我有一个输入列表['abc','def','asd,trp','faq']

预期输出列表['abc','def','asd','trp','faq']

请帮助实现同样的目标

【问题讨论】:

  • 只能接受一个答案。

标签: python pandas list


【解决方案1】:

您可以遍历列表并检查是否存在逗号,如果存在,则拆分和扩展,如果不存在,则附加到输出列表。

lst = ['abc','def','asd,trp','faq']
out = []
for item in lst:
    if ',' in item:
        out.extend(item.split(','))
    else:
        out.append(item)

输出:

['abc', 'def', 'asd', 'trp', 'faq']

既然你标记了pandas,使用pandas,你也可以这样做:

out = pd.Series(lst).str.split(',').explode().tolist()

【讨论】:

    【解决方案2】:

    在列表理解中使用split

    L = ['abc','def','asd,trp','faq']
    
    L1 = [y for x in L for y in x.split(',')]
    print (L1)
    ['abc', 'def', 'asd', 'trp', 'faq']
        
    

    【讨论】:

      猜你喜欢
      • 2011-07-20
      • 1970-01-01
      • 2011-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      相关资源
      最近更新 更多