【发布时间】:2012-02-13 01:20:05
【问题描述】:
递归列表由一串对表示。每对的第一个元素是列表中的一个元素,而第二个是代表列表其余部分的对。最后一对的第二个元素是 None,表示列表已经结束。我们可以使用嵌套的元组文字来构造这个结构。示例:
(1, (2, (3, (4, 无))))
到目前为止,我已经创建了一个将值元组或值 None 转换为相应 rlist 的方法。该方法称为 to_rlist(items)。示例:
>>> to_rlist((1, (0, 2), (), 3))
(1, ((0, (2, None)), (None, (3, None))))
如何编写 to_rlist 的逆函数,该函数将 rlist 作为输入并返回相应的元组?该方法应称为 to_tuple(parameter)。应该发生的事情的例子:
>>> x = to_rlist((1, (0, 2), (), 3))
>>> to_tuple(x)
(1, (0, 2), (), 3)
注意:to_rlist 方法按预期工作。
这是我目前所拥有的:
def to_tuple(L):
if not could_be_rlist(L):
return (L,)
x, y = L
if not x is None and not type(x) is tuple and y is None:
return (x,)
elif x is None and not y is None:
return ((),) + to_tuple(y)
elif not x is None and not y is None:
return to_tuple(x) + to_tuple(y)
这给了我以下结果(这是不正确的):
>>> x = to_rlist((1, (0, 2), (), 3))
>>> to_tuple(x)
(1, 0, 2, (), 3)
如何修复我的方法以正确返回嵌套元组?
【问题讨论】:
-
递归列表是一个包含对自身的引用的列表。
-
@wim 它也可能表示“根据自身定义的列表类型”,在这种情况下它适合。 (这也可能是作业使用的术语,它可以保留的另一个原因。)
-
@user1140118:Stack Overflow 不是一个“为我做(部分)我的家庭作业”的网站。您应该自己开始使用该功能,并就您遇到的具体问题提出问题。