【问题标题】:Counting the number of occurrences and compare to another list计算出现次数并与另一个列表进行比较
【发布时间】:2020-07-22 15:25:21
【问题描述】:

我正在使用 4D 列表计算出现次数,然后与我用作参考的 3D 列表进行比较,我能够做到,但在比较过程中遇到问题,这是我的代码:

from collections import Counter

reference = [[[2, 3], [2, 4], [3, 2], [4, 2]], 
             [[2, 3], [3, 2], [3, 4], [4, 3]], 
             [[2, 3], [3, 2], [3, 4], [4, 3]]]

#This is my 4D list
coord = [[[[4, 2], [2, 3]], [[4, 3], [4, 3]], [[3, 2], [2, 3], [3, 4]]], [[[4, 2], [2, 3]], [[4, 3], [4, 3]], [[3, 2], [2, 3], [3, 4]]]]

#To count the numbers of occurrences
occurrences = [[Counter(tuple(j) for j in i) for i in k] for k in coord]

print(occurrences)

ocurrences = [[Counter({(4, 2): 1, (2, 3): 1}), Counter({(4, 3): 2}), Counter({(3, 2): 1, (2, 3): 1, (3, 4): 1})], [Counter({(4, 2): 1, (2, 3): 1}), Counter({(4, 3): 2}), Counter({(3, 2): 1, (2, 3): 1, (3, 4): 1})]]

到目前为止一切顺利,它从 4D 列表中创建了一个列表 Counter,前 3 个 Counter 对应于 4D 列表中的第一个 3D 列表,接下来的 3 个 Counter 为其他 3D 列表。现在我需要将occurrences 的第一个列表与reference 列表进行比较,然后将occurrences 的第二个列表与相同的引用列表进行比较。这就是我所做的:

out = [[[k[tuple(j)] for j in i] for k in cntr] for i,cntr in zip(reference,occurrences)]

print(out)

out = [[[1, 0, 0, 1], [0, 0, 0, 0], [1, 0, 1, 0]], [[1, 0, 0, 0], [0, 0, 0, 2], [1, 1, 1, 0]]]

例如,第一个Counter(4, 2): 1, (2, 3):1,如果我将匹配键与reference 的第一个列表进行比较,即[[2, 3], [2, 4], [3, 2], [4, 2]] ,我应该得到[1, 0, 0, 1],这确实是我得到的,但第二个@987654334 @ 是(4, 3): 2 ,如果我比较两个参考列表,我应该得到[0, 0, 0, 2],但我得到的是[0, 0, 0, 0],这是错误的。这是我想要的输出:

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

这只是一个简化的例子,我认为它必须对循环做一些事情,但我不确定是什么问题,所以任何想法都会很棒,谢谢!

【问题讨论】:

  • 这只是一个小注释,但 out = [[[k[tuple(j)] for j in i] for k in cntr] for i,cntr in zip(reference,occurrences)] 很难阅读,并且在显式 for 循环中可能会更清晰(在我看来)。

标签: python list dictionary list-comprehension


【解决方案1】:

浏览ocurrences 中的每个计数器列表,然后从相应的计数器中获取reference(作为元组)中每个元素的频率

>>> [[[occ[i][tuple(r)] for r in ref] for i,ref in enumerate(reference)] for occ in ocurrences]
[[[1, 0, 0, 1], [0, 0, 0, 2], [1, 1, 1, 0]], [[1, 0, 0, 1], [0, 0, 0, 2], [1, 1, 1, 0]]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多