【发布时间】:2023-04-02 16:52:02
【问题描述】:
我正在解决一个问题,但我遇到了障碍,我希望你能帮助我,所以基本上我有一个 3D 坐标列表,我正在与另一个我用作参考的 3D 坐标列表进行比较.我要做的是计算坐标的出现次数并将出现次数与参考列表匹配。为此,我将coordinates list 转换为tuples,然后使用Counter 计算出现次数,我需要将Count 中的key 与reference list 中的坐标匹配并存储列表列表中的values。也许代码会比我解释得更好。这是我的代码
from collections import Counter
reference = [[[2, 3], [3, 2], [3, 4], [4, 3]],
[[2, 3], [2, 4], [3, 2], [4, 2]], #3D References list with all the coordinates.
[[2, 3], [2, 4], [3, 2], [4, 2]]]
coordinates = [[[3, 2]], [[3, 2], [2, 4], [2, 4]], [[2, 4]]] #List to match the reference list
newlist = [[tuple(j) for j in i] for i in coordinates] #Transform the coordinates list to tuple to use Counter
aux = []
for i in newlist:
aux.append(Counter(i)) #Count the number of occurrences.
print(aux)
#aux = [Counter({(3, 2): 1}), Counter({(2, 4): 2, (3, 2): 1}), Counter({(2, 4): 1})
a = [list(i.values()) for i in aux] #Getting only the values of occurrence.
print(a) #a = [[1], [1, 2], [1]]
aux list 中的第一个计数器只有键 (3, 2) 出现 1 次,因此我需要将key 与reference list 的第一个列表上的坐标相匹配,如您在第一个与另一个列表相比,计数器缺少一些keys(坐标),所以我需要那些缺少的坐标值为零。第二个计数器有两个键 (2, 4), (3, 2),对应的值为2和1,与reference list的第二个列表相比,也有一些缺失的坐标,所以它们的值为零,依此类推。这是我想要的输出:
#Output
a = [[0, 1, 0, 0], [0, 2, 1, 0], [0, 1, 0, 0]
有什么方法可以做到这一点?用零值“填充”缺失的坐标?如果你能指出我正确的方向,那就太好了,为我糟糕的英语感到抱歉!非常感谢!
【问题讨论】:
标签: python list dictionary compare