如何知道 Python 类型是否有顺序的概念?什么是序列,真的吗? [英] How to know if a Python type has a concept of order? What is a sequence, really?

查看:96
本文介绍了如何知道 Python 类型是否有顺序的概念?什么是序列,真的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 中的 OrderedDict 不是序列类型,这让我有点吃惊.它有一个顺序的概念,但它不是一个序列.

It's blowing my mind a little bit that OrderedDict in Python is not a sequence type. It has a concept of order, but it's not a sequence.

Python 文档

有七种序列类型:字符串、Unicode 字符串、列表、元组、字节数组、缓冲区和 xrange 对象.

There are seven sequence types: strings, Unicode strings, lists, tuples, bytearrays, buffers, and xrange objects.

对于其他容器,请参阅内置的 dict 和 set 类,以及收藏模块....大多数序列类型支持以下操作......序列类型也支持比较.

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__indexcount.__lt__ 等实现比较.

Those operations corresponding to __contains__, __add__ for concatenation, __getitem__ with integers (in range(len(foo))), __len__, __min__, __slice__, index and count. __lt__ etc implement comparisons.

OrderedDicts 实现了这些方法中的一些,但没有实现其他方法,可能是因为按键(如在 dict 中)或顺序(如在索引中)访问项目的语法糖是相同的.

OrderedDicts implement some of these methods but not others, probably because the syntactic sugar for accessing items by key (as in dict) or order (as in index) is the same.

我知道如果某些东西实现了 __iter__ 我可以遍历它.我怎么能肯定地知道某样东西是否有订单?我会认为这就是序列"的意思,第n项总是第n项.

I know if something implements __iter__ I can loop through it. How can I definitely know if something has an order? I would have thought that is what is meant by "sequence", the nth item is always the nth item.

推荐答案

在鸭子打字世界中,这是一个难题.

In a duck typing world, this is a difficult question.

序列和映射都使用 __getitem__() 分别使用内部索引和键来访问项目.寻找 __getitem__() 方法的可用性并不能将它们区分开来,您需要查看该方法实际做了什么.

Both sequences and mapping use __getitem__() to access items, using inter indexes and keys, respectively. Looking for the availability of the __getitem__() method does not tell them apart, you need to look at what the method actually does.

对于字典,不可能知道 __getitem__() 的整数参数是索引还是键,所以它总是以映射方式工作.

For the dict it is not possible to know whether the integer argument to __getitem__() is an index or a key, so it always works mapping-style.

因此,我认为 dict 根本不是序列,即使它支持迭代.同样适用于集合.

Therefore, I think a dict is not a sequence at all, even though it supports iteration. Same applies to the set.

查看 collections.abc.Sequence 基类可能是最好的测试.对于自定义类型,只需确保它们派生自该基类即可.

Looking at the collections.abc.Sequence base class may be the best test. For custom types, just make sure they are derived from this base class.

这篇关于如何知道 Python 类型是否有顺序的概念?什么是序列,真的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆