I want to count how many times a tuple appears in my ouput 'result' (I refine my former question How to join many “listed” tuples into one tuple in Python?).
So I did this:
from collections import Counter
liste = [1,2,3,5,10]
liste2 = [[1,2,3,5,10], [1,2], [1,5,10], [3,5,10], [1,2,5,10]]
for elt in liste2:
syn = elt # identify each sublist of liste2 as syn
nTuple = len(syn) # number of elements in the syn
for i in liste:
myTuple = ()
if syn.count(i): # check if an item of liste is in liste2
myTuple = (i, nTuple)
if len(myTuple) == '0': # remove the empty tuples
del(myTuple)
else:
result = [myTuple]
c = Counter(result)
for item in c.items():
print(item)
and I got these results:
((1, 5), 1)
((2, 5), 1)
((3, 5), 1)
((5, 5), 1)
((10, 5), 1)
((1, 2), 1)
((2, 2), 1)
((1, 3), 1)
((5, 3), 1)
((10, 3), 1)
((3, 3), 1)
((5, 3), 1)
((10, 3), 1)
((1, 4), 1)
((2, 4), 1)
((5, 4), 1)
((10, 4), 1)
Instead of having some elts N times (e.g ((5, 3), 1) and ((10, 3), 1) appear twice), I would like to have a tuple(key,value) where value = the number of times key appears in 'result'.
I would like to get 'result' like this:
((1, 5), 1)
((2, 5), 1)
((3, 5), 1)
((5, 5), 1)
((10, 5), 1)
((1, 2), 1)
((2, 2), 1)
((1, 3), 1)
((5, 3), 2)
((10, 3), 2)
((3, 3), 1)
((1, 4), 1)
((2, 4), 1)
((5, 4), 1)
((10, 4), 1)
Thanks