Reputation: 349
I'm working with 4D list counting the numbers of occurrences and then compare to a 3D list that I use for reference , I was able to do it, but I'm having problem during the comparison, this is my code:
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})]]
So far so good, It creates a list of list of Counter
out of the 4D list, the first 3 Counter
correspond to the first 3D list in the 4D list, and the next 3 Counter
for the other 3D list. Now I need to compare the first list of occurrences
with the reference
list and then the second list of occurrences
with the same references list. This is what I did:
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]]]
For example the first Counter
is (4, 2): 1, (2, 3):1
if I compare the matching keys to the first list of reference
ie [[2, 3], [2, 4], [3, 2], [4, 2]]
I should get [1, 0, 0, 1]
which is indeed what I get, but the second Counter
is (4, 3): 2
and if I compare two the second list of reference I should get [0, 0, 0, 2]
but I'm getting [0, 0, 0, 0]
which is wrong. This is my desired output:
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]]]
This is just an example just to simplify, I think it has to do something with the loop, but I'm not sure what is the problem, so any idea would be great, thank you!
Upvotes: 0
Views: 110
Reputation: 2537
Navigate through each of the list of Counters in ocurrences
and then get the frequency of each element in reference
(as a tuple) from the corresponding counter
>>> [[[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]]]
Upvotes: 2