[英]Python - conversion of string to list of sets
I have a list of strings like ['abc,bcd,cde,def,bcd', 'ijk,jkl', 'lmn,mno,nop,mno' ]
and I am trying to convert into list of sets of strings as given below我有一个像
['abc,bcd,cde,def,bcd', 'ijk,jkl', 'lmn,mno,nop,mno' ]
的字符串列表,我正在尝试将其转换为给定的字符串集列表以下
[{'abc','bcd', 'cde', 'def'}, {'ijk','jkl'}, {'lmn','mno','nop'}]
I have tried to loop through each item in the list and used a set() function to convert but it returned each character instead of a each string as shown below我试图遍历列表中的每个项目并使用 set() 函数进行转换,但它返回每个字符而不是每个字符串,如下所示
L= ['abc,bcd,cde,def,bcd', 'ijk,jkl', 'lmn,mno,nop,mno' ]
for i in L:
print(set(i))
output:输出:
{'b','c','d','e','a','f'}
{'j','i','k','l'}
{'m','l','n','o','p'}
My desired output: [{'abc','bcd', 'cde', 'def'}, {'ijk','jkl'}, {'lmn','mno','nop'}]
我想要的输出:
[{'abc','bcd', 'cde', 'def'}, {'ijk','jkl'}, {'lmn','mno','nop'}]
Can you please give ideas on what am I doing wrong.. (I am novice to Python)你能告诉我我做错了什么吗..(我是 Python 的新手)
You can do this fast and easy by just spliting the strings where you find commas.只需在找到逗号的位置拆分字符串,即可快速轻松地完成此操作。
string_list = ['abc,bcd,cde,def,bcd', 'ijk,jkl', 'lmn,mno,nop,mno']
string_sets = []
for string in string_list:
string_sets.append(set(string.split(",")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.