【问题标题】:Are there any built-in containers other than dict, list, set, and tuple?除了 dict、list、set 和 tuple 之外,还有没有内置的容器?
【发布时间】:2019-11-06 00:33:14
【问题描述】:

dict、list、set 和 tuple 是 Python 的内置容器。

除了上述之外,还有其他内置容器吗?

“内置容器”一词来自the doc

【问题讨论】:

  • 是的,这就是存在的一切。我不明白为什么有人需要更多
  • 你在考虑什么? collections 模块包含很多,multiprocessing 包含 Queue 类。还有很多其他的。
  • frozenset 从来没有得到任何赞赏:p
  • 致癌这些是主要的。其余的存在是这 4 个容器的细分
  • 这完全取决于你的对“内置容器”的定义。您引用的文档仅将这四个归类为“通用内置容器”。 frozenset 也是内置的,但很少使用。 strbytes 和其他都是容器,但仅适用于特定类型。上面还有two meanings for "built-in" in Python

标签: python


【解决方案1】:

从技术上讲,Python 容器是任何实现 __contains__ 方法 (source) 的东西。因此,如果我们只考虑内置函数,而不考虑标准库,我们可以通过这行得到答案:

>>> [i for i in dir(__builtins__) if hasattr(eval(i), '__contains__')]
['_', '__name__', 'bytearray', 'bytes', 'dict', 'frozenset', 'list', 'range', 'set', 'str', 'tuple']

我们希望排除 ___name__,因此完整列表如下:

bytearraybytesdictfrozensetlistrangesetstrtuple


或者,

>>> [k for k, v in vars(__builtins__).items() if hasattr(v, '__contains__')]
['__name__', '__doc__', '__package__', 'bytearray', 'bytes', 'dict', 'frozenset', 'list', 'range', 'set', 'str', 'tuple', '_']

删除 __name____doc____package___ 将得到相同的结果。

【讨论】:

  • 不要在这里使用dir
  • @juanpa.arrivillaga 需要详细说明吗?
  • dir主要用于调试,使用vars返回模块的命名空间,然后可以遍历名称和值,所以[name for name, value in vars(__builtins__).items() if hasattr(value, '__contains__')]
【解决方案2】:

取决于您所说的“容器”是什么意思。 strbytesbytearraymemoryview 呢? frozensetmodule 也可以被视为一个容器。

【讨论】:

  • 谢谢! “内置容器”一词来自the doc
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-01
  • 2021-07-29
  • 2021-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多