Having a list like this, I can get groups of the same values by:
N = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
C = Counter(N)
print([[k, ] * v for k, v in C.items()])
getting the following result.
[[1],[2,2],[3,3,3],[4,4,4,4],[5,5,5,5,5]]
However if I have the following list
N = [{'doc':'A','value':300,'W':1},{'doc':'B','value':301,'W':0.5},{'doc':'C','value':301,'W':0.45},{'doc':'D','value':301,'W':0.3},{'doc':'E','value':300,'W':1},]
I want to group in the same way that the previous one, using the key 'value' to group them, namely:
[[{'doc':A,'value':300,'W':1}, {'doc':'E','value':300,'W':1}],[{'doc':'B','value':301,'W':0.5},{'doc':'C','value':301,'W':0.45},{'doc':'D','value':301,'W':0.3}]]
Can somebody help?
You can use collections.defaultdict
for this problem.
collections.Counter
is only useful for incrementing integer counters, and even then only with hashable objects. This isn't what you are looking to do here.
from collections import defaultdict
N = [{'doc':'A','value':300,'W':1}, {'doc':'B','value':301,'W':0.5},
{'doc':'C','value':301,'W':0.45}, {'doc':'D','value':301,'W':0.3},
{'doc':'E','value':300,'W':1},]
d = defaultdict(list)
for i in N:
d[i['value']].append(i)
res = list(d.values())
# [[{'W': 1, 'doc': 'A', 'value': 300}, {'W': 1, 'doc': 'E', 'value': 300}],
# [{'W': 0.5, 'doc': 'B', 'value': 301},
# {'W': 0.45, 'doc': 'C', 'value': 301},
# {'W': 0.3, 'doc': 'D', 'value': 301}]]
As an aside, this also presents a more direct solution to your first problem:
N = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
d = defaultdict(list)
for i in N:
d[i].append(i)
res = list(d.values())
# [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]