将列表与 Python 中的省略号进行比较
Comparing Lists with Ellipsis in Python
有什么方法可以比较在 Python 中引用自身的列表?您可以在下面看到我尝试过的内容:
In[65]: b
Out[65]: [[...]]
In[66]: a
Out[66]: [[[[...]]]]
In[67]: a==b
Traceback (most recent call last):
File "<ipython-input-67-67c639108cf0>", line 1, in <module>
a==b
RecursionError: maximum recursion depth exceeded in comparison
我能理解它不能永远进入列表,但是还有办法比较带有省略号的列表吗?
[编辑]:
如何创建 a
:
a=[]
a.append(a)
a=[[[a]]]
如何创建 b
:
b=[]
b.append(b)
b=[b]
使用 all
和一个基于列表理解的生成器,我们可以实现一个 compare
函数,它适用于我能弄清楚的所有情况:
def compare(list1: list, list2: list, root1=None, root2=None):
"""Compare recursively nested lists."""
root1, root2 = (root1, root2) if root1 and root2 else (list1, list2)
return len(list1) == len(list2) and all(
((a, b) == (root1, root2) or a == b)
and compare(list1[i + 1:], list2[i + 1:], root1, root2)
for i, (a, b) in enumerate(zip(list1, list2)))
例子
为了便于理解,我将按照打印时的表示来编写列表,而不是使用 appends
不断构建它们。
a, b = ([[...]], [[...]])
compare(a, b)
>>> True
a, b = ([[...], 2], [[...]])
compare(a, b)
>>> False
a, b = ([2, [...], 2], [[...]])
compare(a, b)
>>> False
a, b = ([2, [...], 2], [2, [...], 2])
compare(a, b)
>>> True
a, b = ([2, [...], [2]], [2, [...], [3]])
compare(a, b)
>>> False
如果你想让我测试并添加更多案例,我会很乐意去做。
有什么方法可以比较在 Python 中引用自身的列表?您可以在下面看到我尝试过的内容:
In[65]: b
Out[65]: [[...]]
In[66]: a
Out[66]: [[[[...]]]]
In[67]: a==b
Traceback (most recent call last):
File "<ipython-input-67-67c639108cf0>", line 1, in <module>
a==b
RecursionError: maximum recursion depth exceeded in comparison
我能理解它不能永远进入列表,但是还有办法比较带有省略号的列表吗?
[编辑]:
如何创建 a
:
a=[]
a.append(a)
a=[[[a]]]
如何创建 b
:
b=[]
b.append(b)
b=[b]
使用 all
和一个基于列表理解的生成器,我们可以实现一个 compare
函数,它适用于我能弄清楚的所有情况:
def compare(list1: list, list2: list, root1=None, root2=None):
"""Compare recursively nested lists."""
root1, root2 = (root1, root2) if root1 and root2 else (list1, list2)
return len(list1) == len(list2) and all(
((a, b) == (root1, root2) or a == b)
and compare(list1[i + 1:], list2[i + 1:], root1, root2)
for i, (a, b) in enumerate(zip(list1, list2)))
例子
为了便于理解,我将按照打印时的表示来编写列表,而不是使用 appends
不断构建它们。
a, b = ([[...]], [[...]])
compare(a, b)
>>> True
a, b = ([[...], 2], [[...]])
compare(a, b)
>>> False
a, b = ([2, [...], 2], [[...]])
compare(a, b)
>>> False
a, b = ([2, [...], 2], [2, [...], 2])
compare(a, b)
>>> True
a, b = ([2, [...], [2]], [2, [...], [3]])
compare(a, b)
>>> False
如果你想让我测试并添加更多案例,我会很乐意去做。