Use frozenset as a pair in python

后端 未结 4 678
轮回少年
轮回少年 2021-02-06 06:37

I would like to make a pair of two elements. I don\'t care about the order of the elements, so I use frozenset.

I can think of the following two methods t

4条回答
  •  忘掉有多难
    2021-02-06 07:03

    Just to elaborate on an above comment, and assuming your elements are easily sortable, you could make an unordered pair class from tuple using:

    class Pair(tuple):
        def __new__(cls, seq=()):
            assert len(seq) == 2
            return tuple.__new__(tuple, sorted(seq))
    

    Then you get:

    >>> Pair((0, 1))
    (0, 1)
    
    >>> Pair((1, 0))
    (0, 1)
    
    >>> Pair((0, 1)) == Pair((1, 0))
    True
    

提交回复
热议问题