[英]Searching within Nested lists in Python || How do I match a 1-index nested list, with a 2-index nested list
here is the problem I am trying to solve:这是我要解决的问题:
coord = [[0, 0], [1, 0], [1, 1], [2, 0], [2, 1], [2, 1], [2, 2] ..]
new_arr = [[[0, 0], 1], [[1, 0], 1], [[1, 1], 1], [[2, 0], 1], [[2, 1], 2], [[2, 2], 1] ..]
This is the target I am trying to map to这是我试图 map 的目标
[0, 0][0, 1][0, 2]
[1, 0][1, 1][1, 2]
[2, 0][2, 1][2, 2]
the ultimate output would be the counts against each of the coordinates最终的 output 将是针对每个坐标的计数
1 0 0
1 1 0
1 2 1
------ clarifications -------- ------ 澄清--------
the goal is to generate this square of numbers (counts) which is the second element in new_arr.目标是生成这个数字平方(计数),它是 new_arr 中的第二个元素。 Eg [[0, 0], 1], [[1, 0], 1], can be interpreted as the value 1 for the coordinate [0,0] and value 1 for coordinate [1,0]
例如 [[0, 0], 1], [[1, 0], 1],可以解释为坐标 [0,0] 的值 1 和坐标 [1,0] 的值 1
the first list (coord) is simply a map of the coordinates.第一个列表(坐标)只是坐标的 map。 The goal is to get the corresponding value (from new_arr) and display it in the form of a square.
目标是获取对应的值(来自new_arr)并以正方形的形式显示。 Hope this clarified.
希望这一点得到澄清。 The output will be a grid of the format
output 将是格式的网格
1 0 0
1 1 0
1 2 1
to the question of N (I just took a sample value of 3).对于 N 的问题(我只是取了一个样本值 3)。 The actual use case is when the user enters an integer, say 6 and the result is in a 6 X 6 square.
实际用例是当用户输入 integer,比如 6,结果是 6 X 6 的正方形。 The counts are chess move computations on the ways to reach a specific cell (two movements only (i+1, j) & (i+1, j+1)....... starting from (0,0)
计数是关于到达特定单元格的方式的国际象棋移动计算(仅两个移动 (i+1, j) & (i+1, j+1).......从 (0,0) 开始
The logic is not fully clear, but is looks like you want to map the values of new_arr
on the Cartesian product of coordinates:逻辑并不完全清楚,但看起来你想要 map 坐标的笛卡尔积上的
new_arr
值:
N = 3 # how this is determined is unclear
d = {tuple(l):x for l, x in new_arr}
# {(0, 0): 1, (1, 0): 1, (1, 1): 1, (2, 0): 1, (2, 1): 2, (2, 2): 1}
out = [d.get((i,j), 0) for i in range(N) for j in range(N)]
# [1, 0, 0, 1, 1, 0, 1, 2, 1]
# 2D variant
out2 = [[d.get((i,j), 0) for j in range(N)] for i in range(N)]
# [[1, 0, 0],
# [1, 1, 0],
# [1, 2, 1]]
import numpy as np
N = 3
a = np.zeros((N,N), dtype=int)
# get indices and values
idx, val = zip(*new_arr)
# assign values (option 1)
a[tuple(zip(*idx))] = val
# assign values (option 2)
a[tuple(np.array(idx).T.tolist())] = val
print(a)
output: output:
array([[1, 0, 0],
[1, 1, 0],
[1, 2, 1]])
Use numpy
:使用
numpy
:
import numpy as np
i = []
coord = [[0, 0], [1, 0], [1, 1], [2, 0], [2, 1], [2, 1], [2, 2]]
new_arr = [[[0, 0], 1], [[1, 0], 1], [[1, 1], 1], [[2, 0], 1], [[2, 1], 2], [[2, 2], 1]]
result = np.zeros([coord[-1][0] + 1, coord[-1][1] + 1])
for i in new_arr:
for j in coord:
if i[0] == j:
result[j[0],j[1]]= i[1]
print(result)
Output: Output:
[[1. 0. 0.]
[1. 1. 0.]
[1. 2. 1.]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.