简体   繁体   中英

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'}, {'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

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'}]

Can you please give ideas on what am I doing wrong.. (I am novice to 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(",")))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM