【问题标题】:reshape 2d list重塑二维列表
【发布时间】:2014-12-29 08:05:23
【问题描述】:

我正在尝试实现此功能,但我不确定具体如何实现。我知道我们必须使用 for 循环来解决这个问题,但与设置变量等一样,或者它是否包含嵌套的 for 循环,我不确定。

def reshape(thelist, rows, cols):
    """Returns: A rows*cols 2D list with the contents of thelist

    Hint:  In a 2D list, the element at row x and col y is the
    x*cols+y element listed.

    Example: reshape([1,2,3,4],2,2) returns [[1,2], [3,4]]
    Example: reshape([1,2,3,4,5,6],3,2) returns [[1,2], [3,4], [5,6]]
    Example: reshape([1,2,3,4,5,6],2,3) returns [[1,2,3] ,[4,5,6]]

    Precondition: thelist is a list of numbers of size rows*cols. rows
    and cols are positive integers."""

【问题讨论】:

  • 你为什么不尝试一种方法并显示你有问题的地方呢?一个问题不仅有一个可能的答案。

标签: python for-loop multidimensional-array


【解决方案1】:
def reshape(thelist, rows,cols):  
    parent_list = []
    count = 0
    for j in range(rows):
        new_list = []
        for i in range(cols):
            new_list.append(thelist[count])
            count+=1
        parent_list.append(new_list)
    return parent_list

【讨论】:

  • 这可以在没有嵌套循环的情况下完成,但是这种方法对于初学者来说更清晰易懂。
【解决方案2】:

What is the most “pythonic” way to iterate over a list in chunks?:

def reshape(thelist, rows,cols):  
    return [thelist[i:i + cols] for i in range(0, len(thelist), cols)]

如果你不需要保留类型,你也可以写成zip(*[iter(thelist)]*cols)。请参阅链接问题中的说明。

【讨论】:

    【解决方案3】:

    我能想到的最简单的方法是这样的:

    def thesplit(input_list, rows, cols):
        output_list = []
        for i in range(rows):
            pos = i*cols
            output_list.append(input_list[pos:pos+cols])
        return output_list
    

    如果你不想要变量 pos,你可以使用这个来代替:

    output_list.append(input_list[(i*pos):((i+1)*pos)])
    

    与上一个示例相同。

    【讨论】:

      【解决方案4】:

      这只是 J.F. Sebastian 的第二个解决方案的扩展:

      def reshape(seq, rows, cols):
          return [list(u) for u in zip(*[iter(seq)] * cols)]
      
      rows, cols = 3, 4
      seq = range(rows * cols)
      print reshape(seq, rows, cols)
      

      输出

      [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
      

      我最初发现这个算法有点令人费解。理解它如何工作的关键是要意识到[iter(seq)] * cols 创建了一个cols 引用列表,该列表引用了 same 迭代器 not cols 独立迭代器。因此,每次zip 从其中一个条目中提取一个值时,它都会有效地从原始列表中获取下一个条目。因此,编写基本相同算法的另一种方法是:

      def reshape(seq, rows, cols):
          g = iter(seq)
          return [[g.next() for j in range(cols)] for i in range(rows)]
      

      【讨论】:

        猜你喜欢
        • 2023-02-19
        • 1970-01-01
        • 2019-09-04
        • 2019-03-14
        • 2014-04-21
        • 2019-02-01
        • 2021-03-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多