Case-insensitive comparison of sets in Python

后端 未结 4 1087

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:06

    Here's version that works for any pair of iterables:

    def intersection(iterableA, iterableB, key=lambda x: x):
        """Return the intersection of two iterables with respect to `key` function.
    
        """
        def unify(iterable):
            d = {}
            for item in iterable:
                d.setdefault(key(item), []).append(item)
            return d
    
        A, B = unify(iterableA), unify(iterableB)
    
        return [(A[k], B[k]) for k in A if k in B]
    

    Example:

    print intersection('Today I am fine'.split(),
                       'Hello How a re you TODAY'.split(),
                       key=str.lower)
    # -> [(['Today'], ['TODAY'])]
    

提交回复
热议问题