简体   繁体   English

通过对角填充元素将列表转换为矩阵

[英]Converting a list into a matrix by diagonally filling up the elements

I have a sorted list which looks as below:我有一个sorted list ,如下所示:

mylist = [-2, -2, 1, 1, 4, 4, 3, 3, 3]

The list is sorted in ascending order based upon the number of times it appears.该列表根据其出现的次数按升序排序。 In case of a tie, the list is sorted based upon the values.在平局的情况下,列表将根据值进行排序。

I need to convert this list into a square matrix of equal chunks(3*3 in this case) such that the numbers are placed "diagonally" starting from the bottom right corner .我需要将此列表转换square matrix of equal chunks(3*3 in this case) ,以便数字"diagonally" starting from the bottom right corner放置。

The general case is to divide the list in equal chunks.一般情况是将列表分成相等的块。

Desired Output:所需的 Output:

res = [[3, 3, 4],
      [3, 4, 1],
      [1, -2, -2]]

I have written the below code but still not able to get the desired output:我已经编写了以下代码,但仍然无法获得所需的 output:

def create_matrix(lst, n):
    for i in range(0, len(lst), n):
        print(i)
        yield lst[i: i+n]

m = create_matrix(mylist, 3)

print(list(m))

One solution could be to place pairs in queue/stack and then pop as needed.一种解决方案可能是将对放在队列/堆栈中,然后根据需要弹出。

I assume you want to iterate the output matrix this way (NxN = 5x5 example, 0->24 order):我假设您想以这种方式迭代 output 矩阵(NxN = 5x5 示例,0->24 顺序):

[[ 0,  1,  3,  6, 10],
 [ 2,  4,  7, 11, 15],
 [ 5,  8, 12, 16, 19],
 [ 9, 13, 17, 20, 22],
 [14, 18, 21, 23, 24]]

For each cell, the coordinates (i,j) have their sum equal to the number of the diagonal ( k ) from top-left to bottom right (2*N-1 diagonals in total)对于每个单元格,坐标 (i,j) 的总和等于从左上角到右下角的对角线 ( k ) 的数量(总共 2*N-1 条对角线)

For the N first diagonals, the first item has i=0 , the following ones i=kN where k is the diagonal number.对于 N 个第一个对角线,第一项具有i=0 ,以下是i=kN ,其中k是对角线数。

The last item has i=k with a maximum of N .最后一项具有i=k ,最大值为N

j = ki

This gives us the following algorithm to iterate the cells in order:这为我们提供了以下算法来按顺序迭代单元格:

import math

mylist = [-2, -2, 1, 1, 4, 4, 3, 3, 3]

N = int(math.sqrt(len(mylist))) # 3

out = [[None for _ in range(N)]
       for _ in range(N)]

r = reversed(mylist)

for k in range(2*N-1):
    start = 0 if k<N else k-N+1
    stop = min(k, N-1)
    for i in range(start, stop+1):
        out[i][k-i] = next(r)

print(out)

Output: Output:

[[3, 3, 4],
 [3, 4, 1],
 [1, -2, -2]]

Here's some code to wrap a list backwards up a matrix, which seems to solve this case.这是一些将列表向后包装到矩阵的代码,这似乎解决了这种情况。 Also, your question doesn't make any sense.另外,你的问题没有任何意义。 Diagonally?对角线? And how is that list sorted?该列表是如何排序的?

def create_matrix(lst, n):
    ret = [[0 for i in range(n)] for i in range(n)]
    for i in range(n*n-1,-1,-1):
        ret[i//n][i%n] = lst[n*n-1-i]
    return ret

Edit: That doesn't work.编辑:那是行不通的。 I don't think anyone knows what you mean by diagonally.我想没有人知道你所说的对角线是什么意思。

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

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