首页 文章

如何从特定的数字输入(x,y轴)获取列表?

提问于
浏览
0
Input= 2 2 2 1 2 0 1 0 0 0 0 1

第一个数字是正常XY轴(非列表)中的X坐标,第二个Y坐标,第三个X等等;所以从这个输入看起来像:

Y
2    *
1*   *
0* * *
 0 1 2 X

(第一个*:2,2,第二个*:2,1,第三个*:2,0 - 从右侧开始) .

我需要获得看起来像的输出:

output=
[[0,0,1],
 [1,0,1],
 [1,1,1]]

到目前为止我试过这个,但不知道如何继续:

inp=[2,2,2,1,2,0,1, 0, 0, 0, 0, 1]
maxx=0
maxy=0

for i in range(1,len(inp),2): #yaxis
    if inp[i]>maxy:
        maxy=inp[i]
        continue
    else:
        continue

for j in range(0,len(inp),2): #xaxis
    if inp[j]>maxx:
        maxx=inp[j]
        continue
    else:
        continue

part=[]
for i in range(maxy+1):
    part.append([0 for j in range (maxx+1)])
for k in range(0,len(inp),2):
    for j in range(1,len(inp),2):
        for i in range(len(part)):
            part[i][j]=

1 回答

  • 1
    inp = [2,2,2,1,2,0,1, 0, 0, 0, 0, 1]
    tuples = [(inp[i], inp[i+1]) for i in range(0, len(inp), 2)]
    print(tuples) # [(2, 2), (2, 1), (2, 0), (1, 0), (0, 0), (0, 1)]
    
    # Define the dimensions of the matrix 
    max_x_value = max([i[0] for i in tuples])+1
    max_y_value = max([i[1] for i in tuples])+1
    
    # Build the matrix - fill all cells with 0 for now
    res_matrix = [[0 for _ in range(max_y_value)] for _ in range(max_x_value)]
    
    # Iterate through the tuples and fill the 1's into the matrix
    for i in tuples:
        res_matrix[i[0]][i[1]]=1
    
    print(res_matrix) # [[1, 1, 0], [1, 0, 0], [1, 1, 1]]
    
    # Rotate the matrix by 90 to get the final answer
    res = list(map(list, list(zip(*res_matrix))[::-1]))
    print(res) # [[0, 0, 1], [1, 0, 1], [1, 1, 1]]
    

相关问题