Home > Software design >  get un common strings from 2 array of strings
get un common strings from 2 array of strings

Time:10-05

I have 2 lists like this

first = ['A' , 'B' , 'c' , 'd']
second = ['a' , 'b', 'e']

I want in result ['c' , 'd' ,'e'] . as It's case insensitive and want uncommon from both lists

tried so far :

   a, b = list(set(a) - set(b)),
    list(set(b) - set(a))
 
    print("list1 : ", a)
    print("list2 : ", b)

but not working for case in sensitive

CodePudding user response:

What you want is a difference between the union and the intersection -

(set(map(str.lower, first)) | set(map(str.lower, second))) - (set(map(str.lower, first)) & set(map(str.lower, second)))

Output

{'c', 'd', 'e'}

CodePudding user response:

With these compression lists we can find the uncommon characters while maintaining the incase sensitive strategy. In addition, the output of the function will keep the font (lower, upper) of the original lists:

first = ["A", "B", "c", "d"]
second = ["a", "b", "e"]


def in_case_sensitive(first, second):
    first_unmatched = [f for f in first if f.lower() not in [s.lower() for s in second]]
    second_unmatched = [
        s for s in second if s.lower() not in [f.lower() for f in first]
    ]

    return first_unmatched   second_unmatched


print(in_case_sensitive(first, second))

>>> ['c', 'd', 'e']

with this other lists:

first = ["A", "B", "C", "d"]
second = ["a", "b", "E"]

the output (preserving letter type) is:

>>> ['C', 'd', 'E']

CodePudding user response:

Here's a fairly concise way to do this:

first = ['A', 'B', 'c', 'd']
second = ['a', 'b', 'e']

print(list(set(map(str.lower, first)) ^ set(map(str.lower, second))))

Optionally:

print(list(set(map(str.lower, first)).symmetric_difference(map(str.lower, second))))

Output:

['e', 'd', 'c']

Note:

Note the order of output. If order matters then sort it

  • Related