简体   繁体   English

重塑二维列表

[英]reshape 2d list

I'm trying to implement this function but I'm not sure exactly how to do so. 我正在尝试实现此功能,但是我不确定如何实现。 I know we have to use a for loop for this problem but as with setting with variables and such, or if it contains a nested for loop, I am unsure. 我知道我们必须使用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."""
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

See What is the most “pythonic” way to iterate over a list in chunks? 请参见迭代访问列表中最“ pythonic”的方式是什么? :

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

If you don't need to preserve types, you could also write it as zip(*[iter(thelist)]*cols) . 如果不需要保留类型,也可以将其写为zip(*[iter(thelist)]*cols) See the explanation in the linked question. 请参阅链接问题中的说明。

The simplest way I could think of is this: 我能想到的最简单的方法是:

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

If you do not want the variable pos, you can use this instead: 如果您不想使用变量pos,则可以改用以下命令:

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

which is same as that of the previous sample. 与之前的示例相同。

This is just an expansion of JF Sebastian's 2nd solution: 这只是JF 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)

output 输出

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

I initially found this algorithm a little puzzling. 最初,我发现此算法有些令人费解。 The key to understanding how it works is to realize that [iter(seq)] * cols creates a list of cols references to the same iterator not cols independent iterators. 理解其工作原理的关键是要认识到[iter(seq)] * cols会创建一个对同一迭代器而不是 cols独立迭代器的cols引用列表。 So each time zip pulls a value from one of the entries it effectively gets the next entry from the original list. 因此,每次zip从其中一个条目中提取一个值时,它都会有效地从原始列表中获取下一个条目。 And so another way to write essentially the same algorithm is: 因此,编写基本相同算法的另一种方法是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM