遞歸列表由一對對錶示。每一對中的第一個元素是列表中的一個元素,而第二個元素是一對代表列表的其餘部分。最後一對的第二個元素是None,表示列表已結束。我們可以使用嵌套元組文字構造這個結構。例如:元組和遞歸列表轉換
(1,(2,(3,(4,無))))
到目前爲止,我已經創建了一個方法,其將一個值的元組或值爲None的對應rlist。該方法被稱爲to_rlist(條目)。例如:
>>> to_rlist((1, (0, 2),(), 3))
(1, ((0, (2, None)), (None, (3, None))))
我怎樣寫to_rlist的倒數,其採用的rlist作爲輸入,並返回相應的元組的功能?該方法應該被調用to_tuple(參數)。應該發生什麼的示例:
>>> 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 2012-02-13 01:22:39
@wim它也可能意味着「根據自身定義的列表類型」,在這種情況下它適合。 (這也可能是作業使用的術語,它可以保留的另一個原因。) – millimoose 2012-02-13 01:26:26
@ user1140118:堆棧溢出不是「爲我做的(部分)我的作業」網站。您應該自己開始使用該功能,併發布有關*特定*問題的問題。 – millimoose 2012-02-13 01:27:42