简体   繁体   English

如何在 python 的列表中转换带有逗号分隔值的字符串?

[英]how to convert a string with comma separated values within a list in python?

Hi I'm relatively new to python and not quite getting a resolve for the mentioned issue嗨,我对 python 比较陌生,并没有完全解决上述问题

I have an input list ['abc','def','asd,trp','faq']我有一个输入列表['abc','def','asd,trp','faq']

Expected Output list ['abc','def','asd','trp','faq']预期 Output 列表['abc','def','asd','trp','faq']

please help in achieving the same请帮助实现同样的目标

Use split in list comprehension:在列表理解中使用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']
    

You can iterate over the list and check if a comma exists and if it does, split and extend, if not, append to an output list.您可以遍历列表并检查是否存在逗号,如果存在,则拆分并扩展 append 到 output 列表。

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

Output: Output:

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

Since you tagged pandas, using pandas, you can also do:由于您使用 pandas 标记了 pandas,因此您还可以执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将逗号分隔的字符串转换为 Python 中的项目中包含逗号的列表? - How to convert comma separated string to list that contains comma in items in Python? 如何将包含未用逗号分隔的值列表的字符串转换为列表? - How to convert a string containing a list of values that are not comma-separated to a list? 将浮点数列表转换为逗号分隔的字符串 | Python - Convert list of floats to comma separated string | Python 将逗号分隔的字符串转换为 Python 中的列表项 - Convert comma separated string to list items in Python 将字典列表转换为逗号分隔的字符串 python - Convert list of Dictionaries to comma separated string python 如何在 python 中将逗号分隔的字符串转换为逗号分隔的 int - how to convert comma separated string to comma seperated int in python Python - 将逗号分隔的字符串转换为缩减字符串列表 - Python - convert comma separated string into reducing string list 将python字典转换为逗号分隔的键字符串和逗号分隔值字符串的优雅方法是什么? - What is an elegant way to convert a python dictionary into a comma separated keys string and a comma separated values string? Python pandas将逗号分隔值列表转换为dataframe - Python pandas convert list of comma separated values to dataframe 如何使用 jinja 或 javascript 将 python 中的列表转换为 python 中的逗号分隔值 - How to convert list from python into comma separated values in python with jinja or javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM