Python set with the ability to pop a random element

前端 未结 6 1138
时光说笑
时光说笑 2020-12-30 23:43

I am in need of a Python (2.7) object that functions like a set (fast insertion, deletion, and membership checking) but has the ability to return a random value. Previous qu

6条回答
  •  遥遥无期
    2020-12-31 00:16

    Yes, I'd implement an "ordered set" in much the same way you did - and use a list as an internal data structure.

    However, I'd inherit straight from "set" and just keep track of the added items in an internal list (as you did) - and leave the methods I don't use alone.

    Maybe add a "sync" method to update the internal list whenever the set is updated by set-specific operations, like the *_update methods.

    That if using an "ordered dict" does not cover your use cases. (I just found that trying to cast ordered_dict keys to a regular set is not optmized, so if you need set operations on your data that is not an option)

提交回复
热议问题