Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract all the unique characters from a list of strings efficiently?

I have a list of input variables as:

field_list = ['u', 'w', 'uu', 'uv', 'uw']

I would like to get a list as output containing all the unique characters. If I know beforehand that I’ll only be dealing with ‘u’, ‘v’ and ‘w’, I can write something like

indv_fields = []

for field in field_list:
    if "u" in field:
        indv_fields.append("u")
    if "v" in field:
        indv_fields.append("v")
    if "w" in field:
        indv_fields.append("w")

indv_fields = list(set(indv_fields))
print(indv_fields)

I would like to extend this (and possibly make it more efficient) for a case where I do not know the variables to be extracted beforehand. Let’s say if I received input like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

field_list = ['u', 'v', 'w', 'T', 'ww']

I also want to extract ‘T’ which won’t be possible from the code above. Also, I do not know beforehand what all variables might be there in this list. In such scenario, how do I efficiently extract all the unique elements?

>Solution :

you could just join all the strings together then call set on it.

field_list = ['u', 'w', 'uu', 'uv', 'uw']
print(set("".join(field_list)))

field_list = ['u', 'tw', 'ugu', 'uzv', 'uxw']
print(set("".join(field_list)))

OUTPUT

{'w', 'v', 'u'}
{'t', 'u', 'w', 'x', 'g', 'z', 'v'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading