HelloGitHub 第 100 期

更好用的 Python 排序集合库。该项目提供了 SortedList、SortedDict 和 SortedSet 三种数据结构,完全兼容 List、Dict、Set 内置数据类型的 API。尽管采用纯 Python 编写,其速度却可以媲美使用 C 扩展实现的 Python 库。

from sortedcontainers import SortedList
sl = SortedList(['e', 'a', 'c', 'd', 'b'])
# sl: SortedList(['a', 'b', 'c', 'd', 'e'])
sl *= 10_000_000
sl.count('c')  # 10000000
sl[-3:]  # ['e', 'e', 'e']

from sortedcontainers import SortedDict
sd = SortedDict({'c': -3, 'a': 1, 'b': 2})
# sd: SortedDict({'a': 1, 'b': 2, 'c': -3})
sd.popitem(index=-1)  # ('c', -3)

from sortedcontainers import SortedSet
ss = SortedSet('abracadabra')
# ss: SortedSet(['a', 'b', 'c', 'd', 'r'])
ss.bisect_left('c')  # 2

内容来自 HelloGitHub 月刊,版权归原作者所有。

阅读原文 ↗

把喜欢的内容,留在你的新标签页。

打开我的订阅