Python 为对象引用打印“[...]”是什么意思?

What does Python mean by printing "[...]" for an object reference?

我正在打印一个我认为是列表的值,但我得到的输出是:

[...]

这代表什么?我如何测试它?我试过:

myVar.__repr__() != '[...]'

myVar.__repr_() != Ellipsis

但是没有骰子...

这是导致问题的代码的缩减:

def buildPaths(graph, start, end, path=[], totalPaths=[]):
    """
    returns list of all possible paths from start node to the end node
    """
    path = path + [start]
    if start == end:
        return path
    for nextNode in graph.childrenOf(start):
        if nextNode not in path:
            newPath = buildPaths(graph, nextNode, end, path, totalPaths)
            if newPath != []: # test
                totalPaths.append(newPath)
    return totalPaths

totalPaths 包含很多 [...] 据说是递归列表,但我不明白为什么。我已经在#test 更改了测试以防止这种情况。

我也试过:

def buildPaths(graph, thisNode, end, path=[], totalPaths=None):
    """
   returns list of all possible paths from start node to the end node
   """
    path = path + [thisNode]
    if thisNode == end:
        return path
    for nextNode in graph.childrenOf(thisNode):
        if nextNode not in path:
            newPath = buildPaths(graph, nextNode, end, path, totalPaths)
            if newPath != None:
                if totalPaths == None:
                    totalPaths = [newPath]
                else:
                    totalPaths.append(newPath)
    return totalPaths

为了显式 return None 空路径。

它表示结构内的无限循环。一个例子:

In [1]: l = [1, 2]

In [2]: l[0] = l

In [3]: l
Out[3]: [[...], 2]

l的第一项就是它自己。这是一个递归引用,因此 python 无法合理显示其内容。相反,它显示 [...]

这是一个递归引用,因为您的列表包含自身。 Python 不会尝试递归打印这会导致无限循环。

repr 检测到这一点。因此,如果您查看列表对象的内部表示,您会看到(出现省略号的地方)"Reference to the same list object at address *",其中 * 是原始列表对象在内存中的地址。因此,无限循环。

如果您的列表包含自引用 Python 会将其显示为 [...] 而不是尝试递归打印出来,这会导致无限循环:

>>> l = [1, 2, 3]
>>> print(l)
[1, 2, 3]
>>> l.append(l)
>>> print(l)
[1, 2, 3, [...]]
>>> print(l[-1])        # print the last item of list l
[1, 2, 3, [...]]
>>> print(l[-1][-1])    # print the last item of the last item of list l
[1, 2, 3, [...]]

无穷无尽。

字典也会出现类似的情况:

>>> d = {}
>>> d['key'] = d
>>> print(d)
{'key': {...}}
>>> d['key']
{'key': {...}}
>>> d['key']['key']
{'key': {...}}

根据这里的上下文,它可能会有所不同:

indexing/slicing 与 Ellipsis

我认为它没有为任何 python class 实现,但它 应该 代表任意数量的数据结构嵌套(as非常需要 )。 因此,例如:a[..., 1] 应该 return 最内层嵌套结构的所有第二个元素:

>>> import numpy as np
>>> a = np.arange(27).reshape(3,3,3)  # 3dimensional array
>>> a[..., 1]  # this returns a slice through the array in the third dimension
array([[ 1,  4,  7],
       [10, 13, 16],
       [19, 22, 25]])
>>> a[0, ...]  # This returns a slice through the first dimension
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

并检查此 ... 你将它与 Ellipsis 进行比较(这是一个单例,因此建议使用 is:

>>> ... is Ellipsis
True
>>> Ellipsis in [...]
True
# Another (more or less) equivalent alternative to the previous line:
>>> any(i is Ellipsis for i in [1, ..., 2]) 
True

递归数据结构

您在 输出 中看到 [...] 的另一种情况是,如果序列本身包含序列。在这里它代表一个 infinite 深度嵌套序列(不可打印)。例如:

>>> alist = ['a', 'b', 'c']
>>> alist[0] = alist
>>> alist
[[...], 'b', 'c']

# Infinite deeply nested so you can use as many leading [0] as you want
>>> alist[0][1] 
'b'
>>> alist[0][0][0][0][0][1] 
'b'
>>> alist[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][1] 
'b'

你甚至可以多次替换它:

>>> alist[2] = alist
>>> alist
[[...], 'b', [...]]
>>> alist[1] = alist
>>> alist
[[...], [...], [...]]

要测试输出中是否有任何此类递归,您需要检查数据结构本身是否也是元素之一:

>>> alist in alist
True
>>> any(i is alist for i in alist)
True

获得更有意义的输出的另一种方法是使用 pprint.pprint:

>>> import pprint
>>> pprint.pprint(alist)  # Assuming you only replaced the first element:
[<Recursion on list with id=1628861250120>, 'b', 'c']