Case-insensitive comparison of sets in Python

后端 未结 4 1036

I have two sets (although I can do lists, or whatever):

a = frozenset((\'Today\',\'I\',\'am\',\'fine\'))
b = frozenset((\'hello\',\'how\',\'are\',\'you\',\'t         


        
4条回答
  •  深忆病人
    2021-01-19 16:03

    First, don't you mean a.intersection(b)? The intersection (if case insensitive) would be set(['today']). The difference would be set(['i', 'am', 'fine'])

    Here are two ideas:

    1.) Write a function to convert the elements of both sets to lowercase and then do the intersection. Here's one way you could do it:

    >>> intersect_with_key = lambda s1, s2, key=lambda i: i: set(map(key, s1)).intersection(map(key, s2))
    >>> fs1 = frozenset('Today I am fine'.split())
    >>> fs2 = frozenset('Hello how are you TODAY'.split())
    >>> intersect_with_key(fs1, fs2)
    set([])
    >>> intersect_with_key(fs1, fs2, key=str.lower)
    set(['today'])
    >>>
    

    This is not very efficient though because the conversion and new sets would have to be created on each call.

    2.) Extend the frozenset class to keep a case insensitive copy of the elements. Override the intersection method to use the case insensitive copy of the elements. This would be more efficient.

提交回复
热议问题