Home > Net >  How to union words/find the maximum words in one list or string?
How to union words/find the maximum words in one list or string?

Time:03-25

I have a string like,

str1 = "dogwood;dog;cat;cattree;"

I want to get the union results of this string,like

res = "dogwood;cattree"

how to solve this problem? If string is not convenient, what about

l1 = ["dogwood","dog","cat","cattree"]

P.S the order of list or string is not matter, I only want the maximum words in them.

CodePudding user response:

Just collect the words that aren't in any different word?

res = [word
       for word in l1
       if not any(word in other != word
                  for other in l1)]

CodePudding user response:

Since I assume you'd want to get rid of duplicates as well, this should do:

str1 = "dogwood;dog;cat;cattree;cattree;"

words = str1.split(';')
result = ';'.join({w for w in words if not any(w in o and o != w for o in words)})
print(result)

Result:

dogwood;cattree

CodePudding user response:

When you convert a string to a set, the string is treated as a sequence of characters, so you get a set of all the characters, not a set containing the string.

Just convert the list of strings that you get from split() into a set.

Then use ";".join() to combine them back into a string.

res = ";".join(set(str1[:-1].split(";")))
  • Related