Home > database >  How to find the solution list with python string list manipulation
How to find the solution list with python string list manipulation

Time:06-05

I am looking for a way to find the expected output: Here we have both list contains strings. Please take a look at below input lists:

lst1 =["a: ","b: ","c:","d :"]
lst2 =[" b:"," a:","f:","g:","c: ","d:"]

Expected:

outputlst=["a: ","b: ","c:","d :",f:","g:"] 

Here outputlst will always have lst1 elements whereas their similar lst2 variations "a: "," b: ","c:", "d:" must be removed. I have not reached results so far with list iterations versions.

Any ideas would be appreciated!

CodePudding user response:

Normally, I would recommend using outputlst = list(set(lst1 lst2)) but since there's a slight variation by whitespaces in two ends, you can probably create a list or set (already_contained in below code) to check if a string with trailing whitespaces removed and use it as a check to see if a string in lst2 should be passed to outputlst

lst1 =["a: ","b: ","c:"]
lst2 =[" b:"," a:","f:","g:","c: "]
already_contained = set([c.replace(':', '').strip() for c in lst1])
outputlst = lst1   [c for c in lst2 if c.replace(':', '').strip() not in already_contained]
  • Related