[英]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.