Is there a way I can multiply the elements of a counter object by their count? For example, if I were to multiply the elements of this:
Counter({5: 3, 6: 2, 8: 1})
I would get
{15, 12, 8}
Is there a way I can multiply the elements of a counter object by their count? For example, if I were to multiply the elements of this:
Counter({5: 3, 6: 2, 8: 1})
I would get
{15, 12, 8}
Try to convert Counter object to list of tuples (also set is impossible for being ordered so use list:
>>> c=Counter({5: 3, 6: 2, 8: 1})
>>> [x*y for x,y in c.items()]
[15, 12, 8]
>>>
You can use a list comprehension as per @U9-Forward's solution.
An alternative functional solution is possible with operator.mul and zip:
from collections import Counter
from operator import mul
c = Counter({5: 3, 6: 2, 8: 1})
res = list(map(mul, *zip(*c.items())))
# [15, 12, 8]
If you really need a set, wrap map with set instead of list. The difference is set is an unordered collection of unique items, while list is an ordered collection with no restriction on duplicates.