Python 中的 OrderedDict 不是序列类型,这让我有点惊讶。它有一个顺序的概念,但它不是一个序列。
There are seven sequence types: strings, Unicode strings, lists, tuples, bytearrays, buffers, and xrange objects.
For other containers see the built in dict and set classes, and the collections module. ...Most sequence types support the following operations....Sequence types also support comparisons.
这些操作对应于__contains__
、__add__
(用于连接)、__getitem__
(在range(len(foo))中)
)、__len__
、__min__
、__slice__
、index
和 count
。 __lt__
等实现比较。
OrderedDicts 实现了其中一些方法,但没有实现其他方法,可能是因为通过键(如字典)或顺序(如索引)访问项目的语法糖是相同的。
我知道如果有东西实现了 __iter__
我可以循环遍历它。我怎样才能确切地知道某样东西是否有订单?我本以为这就是“序列”的含义,第 n 项始终是第 n 项。
最佳答案
在鸭子打字世界中,这是一个困难的问题。
两者sequences and mapping使用__getitem__()
分别使用内部索引和键来访问项目。寻找 __getitem__()
的可用性方法并不能区分它们,您需要查看该方法实际上做了什么。
对于字典,不可能知道整数参数是否为 __getitem__()
是索引或键,因此它始终以映射方式工作。
因此,我认为字典根本不是序列,尽管它支持迭代。这同样适用于集合。
查看 collections.abc.Sequence
基类可能是最好的测试。对于自定义类型,只需确保它们是从该基类派生的即可。
关于python - 如何知道Python类型是否有顺序的概念?序列到底是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17521557/