代码之家  ›  专栏  ›  技术社区  ›  gp0478

如何反转子列表中的元素?

  •  4
  • gp0478  · 技术社区  · 8 年前

    我正在尝试创建一个函数,它可以反转列表中元素的顺序,也可以反转子列表中的元素。例如:

    例如,如果L=[[1,2],[3,4],[5,6,7]],那么deep_reverse(L)将L变为[[7,6,5],[4,3],[2,1]]

    我知道了如何反转一个列表的顺序,但在反转子列表中元素的顺序时遇到了困难。这就是我目前掌握的:

    def deep_reverse(L)
        """ 
        assumes L is a list of lists whose elements are ints
        Mutates L such that it reverses its elements and also 
        reverses the order of the int elements in every element of L. 
        It does not return anything.
        """
        for i in reversed(L):
              print(i)
    

    在上面的例子中,我的代码只打印 [5,6,7], [3,4], [1,2] ,这不是我想要实现的。它只是颠倒了列表的顺序,而不是列表中的实际元素。

    我应该向代码中添加什么,以便它也反转子列表中元素的顺序?

    [ 编辑 需要 改变列表;我不想只打印它,它实际上需要更改列表。]

    7 回复  |  直到 8 年前
        1
  •  4
  •   Patrick Haugh    8 年前
    [sublist[::-1] for sublist in to_reverse[::-1]]
    

    列表理解在这里起作用。 [::-1] 基本上与 reversed ,但不会修改列表。

    编辑:

    如下文所述, 颠倒的 不会修改列表。它返回一个 listreverseiterator 对象

    更多编辑:

    def deep_reverse(to_reverse):
        if isinstance(to_reverse, list):
            return list(map(deep_reverse, to_reverse[::-1]))
        else:
            return to_reverse
    

    更多编辑:

    要修改函数中的列表,请执行以下操作:

    L[:] = new_list 
    

    将就地修改列表。

        2
  •  2
  •   Stefan Pochmann    8 年前

    我正在尝试创建一个函数,它可以反转列表中元素的顺序,也可以反转子列表中的元素。

    然后做这两件事:

    L.reverse()
    for sublist in L:
        sublist.reverse()
    

    完整演示,因为您似乎对函数应该做什么以及如何测试感到困惑:

    >>> def deep_reverse(L):
            """ 
            assumes L is a list of lists whose elements are ints
            Mutates L such that it reverses its elements and also 
            reverses the order of the int elements in every element of L. 
            It does not return anything.
            """
            L.reverse()
            for sublist in L:
                sublist.reverse()
    
    >>> L = [[1, 2], [3, 4], [5, 6, 7]]
    >>> deep_reverse(L)
    >>> print(L)
    [[7, 6, 5], [4, 3], [2, 1]]
    
        3
  •  1
  •   Moinuddin Quadri    8 年前

    或者,您可以使用 map() 实现这一目标:

    >>> map(lambda x: x[::-1], L[::-1])       # In Python 2.x
    [[7, 6, 5], [4, 3], [2, 1]]
    
    >>> list(map(lambda x: x[::-1], L[::-1])) # In Python 3.x
    [[7, 6, 5], [4, 3], [2, 1]]
    

    在上检查博客 Lambda, filter, reduce and map 知道如何 lambda 功能和 地图()

        4
  •  1
  •   geo1230    8 年前

    这应该会起作用。

    L = [[1, 2], [3, 4], [5, 6, 7]]
    
    def deep_reverse(L):
        for i in range(len(L)):
            L[i]=L[i][::-1]
        L=L[::-1]
        return L
    
        5
  •  0
  •   Graham francescalus    7 年前

    这看起来很熟悉:)。我不会给出完整的工作解决方案,但这里有一些提示:

    如您所知,有两个步骤,反转每个子列表,然后反转外部列表(就地,不生成新列表,因此它将改变全局 L ).

    因此,您可以循环访问外部列表,并修改每个子列表:

    for i in range(len(L)):
        # if L[i] is a list:
            # reverse with [::-1] and update L[i] to the reversed version
    # reverse the outer list L, list.reverse() will operate in-place on L
    

    现在请记住,如果您像这样循环列表:

    for item in list:
        item = 'xxx'
    

    你不能改变 item 使用上述代码。 项目 是占位符值,因此更改它实际上不会修改列表。

    相反,您需要在中索引该项 L ,enumerate可以帮助实现这一点,或者您可以使用不太受欢迎的 range(len()) 同上。

    for i, item in enumerate(L):
        # do something with L[i]
        L[i] = 'something'
    

    编辑:由于对此有很多困惑,我将根据斯蒂芬·波奇曼非常优雅的回答,发布一个可行的解决方案:

    def deep_reverse(L):
        L.reverse()
        for sublist in L:
            sublist.reverse()
    

    注意这里有 没有return语句,也没有print语句 。这将正确修改 L 在正确的位置你 不能 L 因为这样它将只创建新的本地版本 L ,并且不会修改全局 L 。您可以使用 list.reverse() 修改 L 在正确的位置 根据规范,这是必要的。

        6
  •  0
  •   Manu    7 年前

    使用函数范式和防御性编程:

    def deep_reverse(L):
        """ assumes L is a list of lists whose elements are ints
        Mutates L such that it reverses its elements and also 
        reverses the order of the int elements in every element of L. 
        It does not return anything.
        """
        # Your code here
        for i in L:
            try:
                deep_reverse(i)
            except:
                pass
        L.reverse()
    
        7
  •  -1
  •   Smitje    8 年前

    您可以使其递归,因此它适用于任意深度的嵌套。

    类似于(未测试):

    def deep_reverse(L)
        """ 
        assumes L is a list of lists whose elements are ints
        Mutates L such that it reverses its elements and also 
        reverses the order of the int elements in every element of L. 
        It does not return anything.
        """
        for i in reversed(L):
              if len(i) > 1:
                  deep_reverse(i)
              else:
                  print(i)