Indexable weak ordered set in Python

后端 未结 2 681
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-31 12:27

I was wondering if there is an easy way to build an indexable weak ordered set in Python. I tried to build one myself. Here\'s what I came up with:

\"\"\"
An i         


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-31 12:47

    Raymond has a great and succinct answer, as usual, but I actually came here a while back interested in the indexable part, more than the weakref part. I eventually built my own answer, which became the IndexedSet type in the boltons utility library. Basically, it's all the best parts of the list and set APIs, combined.

    >>> x = IndexedSet(list(range(4)) + list(range(8)))
    >>> x
    IndexedSet([0, 1, 2, 3, 4, 5, 6, 7])
    >>> x - set(range(2))
    IndexedSet([2, 3, 4, 5, 6, 7])
    >>> x[-1]
    7
    >>> fcr = IndexedSet('freecreditreport.com')
    >>> ''.join(fcr[:fcr.index('.')])
    'frecditpo'
    

    If the weakref part is critical you can likely add it via inheritance or direct modification of a copy of the code (the module is standalone, pure-Python, and 2/3 compatible).

提交回复
热议问题