【问题标题】:Matching the number of occurrences of a 3D list with a reference list将 3D 列表的出现次数与参考列表匹配
【发布时间】:2023-04-02 16:52:02
【问题描述】:

我正在解决一个问题,但我遇到了障碍,我希望你能帮助我,所以基本上我有一个 3D 坐标列表,我正在与另一个我用作参考的 3D 坐标列表进行比较.我要做的是计算坐标的出现次数并将出现次数与参考列表匹配。为此,我将coordinates list 转换为tuples,然后使用Counter 计算出现次数,我需要将Count 中的keyreference 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 次,因此我需要将keyreference 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


    【解决方案1】:

    只需浏览来自reference 的每个坐标,然后在aux 的相应计数器中检查该坐标的计数数

    aux = [Counter(tuple(j) for j in i) for i in coordinates]
    a = [[cntr[tuple(j)] for j in i] for i,cntr in zip(reference,aux)]
    print (a)
    # [[0, 1, 0, 0], [0, 2, 1, 0], [0, 1, 0, 0]]
    

    【讨论】:

    • 不好意思打扰了,我还有一个类似的问题,如果你有时间,可以查一下吗?
    猜你喜欢
    • 2021-09-26
    • 2022-08-13
    • 2016-08-26
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2012-07-09
    相关资源
    最近更新 更多