小编use*_*118的帖子

元组和递归列表转换

递归列表由成对的链表示。每对中的第一个元素是列表中的元素,而第二对是代表列表其余部分的对。最后一对的第二个元素为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 …
Run Code Online (Sandbox Code Playgroud)

python tuples sequence

5
推荐指数
1
解决办法
4897
查看次数

标签 统计

python ×1

sequence ×1

tuples ×1