【问题标题】:Tuple and recursive list conversion元组和递归列表转换
【发布时间】: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 不是一个“为我做(部分)我的家庭作业”的网站。您应该自己开始使用该功能,并就您遇到的具体问题提出问题。

标签: python tuples sequence


【解决方案1】:
def to_list(x):
    if x == None:
        return ()
    if type(x) != tuple:
        return x
    a, b = x
    return (to_list(a),) + to_list(b)

【讨论】:

  • 1.使用x is None 与单例进行比较 2. 使用isinstance 进行类型检查,以便代码仍然适用于继承的类 3. 当您看到homework 标记时,不要只是发布解决方案。帮助学生找出他们自己的工作需要改进的地方。
  • 我尝试了解决方案,但只能将元组(不是“str”)连接到元组有什么问题?
【解决方案2】:

这个对我的硬件有用;)

def to_rlist(items):
    r = empty_rlist
    for i in items[::-1]:
        if is_tuple(i): r1 = to_rlist(i)
        else: r1 = i
        r = make_rlist(r1,r)
    return r

【讨论】:

  • 什么是empty_rlist,什么是make_rlist?
  • 尊敬的用户,您的回答似乎很有用。虽然,首先提供一些解决方案描述很重要。我们想知道一些动机,以及关于您的问题解决方案的简单而完整的解释。
猜你喜欢
  • 2015-12-03
  • 2015-06-27
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 2019-10-04
  • 2020-05-24
  • 1970-01-01
  • 2012-12-21
相关资源
最近更新 更多