use*_*118 5 python tuples sequence
递归列表由成对的链表示。每对中的第一个元素是列表中的元素,而第二对是代表列表其余部分的对。最后一对的第二个元素为None,表示列表已结束。我们可以使用嵌套元组文字构造此结构。例:
(1,(2,(3,(4,无))))
到目前为止,我已经创建了一种将值的元组或值None转换为相应的rlist的方法。该方法称为to_rlist(items)。例:
>>> to_rlist((1, (0, 2), (), 3))
(1, ((0, (2, None)), (None, (3, None))))
Run Code Online (Sandbox Code Playgroud)
如何编写to_rlist的逆函数,该函数以rlist作为输入并返回相应的元组?该方法应称为to_tuple(parameter)。应发生的情况的示例:
>>> x = to_rlist((1, (0, 2), (), 3))
>>> to_tuple(x)
(1, (0, 2), (), 3)
Run Code Online (Sandbox Code Playgroud)
注意:方法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)
Run Code Online (Sandbox Code Playgroud)
这给了我以下结果(不正确):
>>> x = to_rlist((1, (0, 2), (), 3))
>>> to_tuple(x)
(1, 0, 2, (), 3)
Run Code Online (Sandbox Code Playgroud)
如何修复我的方法以正确返回嵌套元组?
def to_list(x):
if x == None:
return ()
if type(x) != tuple:
return x
a, b = x
return (to_list(a),) + to_list(b)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4897 次 |
| 最近记录: |