Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么正则表达式匹配对象不是';即使它们实现了_ugetItem _;也无法实现?_Python_Iterable - Fatal编程技术网

Python 为什么正则表达式匹配对象不是';即使它们实现了_ugetItem _;也无法实现?

Python 为什么正则表达式匹配对象不是';即使它们实现了_ugetItem _;也无法实现?,python,iterable,Python,Iterable,你可能知道: 但是,这对正则表达式匹配对象不适用: >>> import re >>> match = re.match('(ab)c', 'abc') >>> match[0] 'abc' >>> match[1] 'ab' >>> list(match) Traceback (most recent call last): File "<stdin>", line 1, in <m

你可能知道:

但是,这对正则表达式匹配对象不适用:

>>> import re
>>> match = re.match('(ab)c', 'abc')
>>> match[0]
'abc'
>>> match[1]
'ab'
>>> list(match)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '_sre.SRE_Match' object is not iterable

那么,如何实现
\uuu getitem\uuu
而不使类变得可移植呢?

有谎言,该死的谎言,然后是Python文档

对于一个用C实现的类来说,拥有
\uuuu getitem\uuuu
是不足以使其具有可移植性的。这是因为在
PyTypeObject
中实际上有两个位置可以将
\uu getitem\uuuu
映射到:和。两者都有一个插槽用于
\uuu getitem\uuu
(,)

查看源代码,
tp_as_序列
被初始化为
NULL
,而
tp_as_映射
被定义

iter()
内置函数如果使用一个参数调用,将调用,该函数具有以下代码:

f = t->tp_iter;
if (f == NULL) {
    if (PySequence_Check(o))
        return PySeqIter_New(o);
    return type_error("'%.200s' object is not iterable", o);
}
它首先检查
tp\u iter
插槽(显然
NULL
用于
\u SRE\u Match
对象);如果失败,那么如果
PySequence\u Check
返回true,则会引发一个新的序列迭代器,否则会引发
TypeError

首先检查对象是
dict
还是
dict
子类,在这种情况下返回false。否则,它将返回

s->ob_type->tp_as_sequence &&
    s->ob_type->tp_as_sequence->sq_item != NULL;

由于
s->ob\u type->tp\u as\u sequence
对于
\u SRE\u Match
实例为
NULL
,因此将返回0,和
PyObject\u GetIter
引发
TypeError:“'u sre.sre\u Match'对象不可编辑

我甚至无法下标
Match
。@Sweeper
Match.\u getitem\uuuuu
是在Python 3.6@DeepSpace中添加的。。。我用的是3.5。@PedroLobito,但这没有解释吗?@PedroLobito,这是一个完全不同的问题,不是吗?我的匹配对象确实有一个
\uuuu getitem\uuu
方法。。。
f = t->tp_iter;
if (f == NULL) {
    if (PySequence_Check(o))
        return PySeqIter_New(o);
    return type_error("'%.200s' object is not iterable", o);
}
s->ob_type->tp_as_sequence &&
    s->ob_type->tp_as_sequence->sq_item != NULL;