Multiply elements of a counter object
Multiply elements of a counter object
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
c = Counter(5: 3, 6: 2, 8: 1) print([k*v for k, v in c.items()])
Bloody legend, that was it, thanks man
– John
Sep 7 '18 at 8:15
the resulting object that you claim to be after is a
set
. Are you sure you want a set? If you originally started out with Counter(5: 3, 3: 5)
you would get only 15
. Are you fine with that?– Ev. Kounis
Sep 7 '18 at 8:15
set
Counter(5: 3, 3: 5)
15
2 Answers
2
Try to convert Counter
object to list of tuples (also set
is impossible for being ordered so use list
:
Counter
set
list
>>> c=Counter(5: 3, 6: 2, 8: 1)
>>> [x*y for x,y in c.items()]
[15, 12, 8]
>>>
15, 12, 8 == [15, 12, 8] -> False
– Black Thunder
Sep 7 '18 at 8:13
15, 12, 8 == [15, 12, 8] -> False
@BlackThunder Haha, yeah, edited
– U9-Forward
Sep 7 '18 at 8:14
@BlackThunder OP most likely does not know what he is after. Do not be so pedantic. A
set
does not have any order anyhow but one must write it somehow..– Ev. Kounis
Sep 7 '18 at 8:16
set
@BlackThunder Edited mine
– U9-Forward
Sep 7 '18 at 8:16
I think you should also mention that
set
is not useful here - just try Counter(5: 3, 3: 5)
– soon
Sep 7 '18 at 8:16
set
Counter(5: 3, 3: 5)
You can use a list comprehension as per @U9-Forward's solution.
An alternative functional solution is possible with operator.mul
and zip
:
operator.mul
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.
set
map
set
list
set
list
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
c = Counter(5: 3, 6: 2, 8: 1) print([k*v for k, v in c.items()])
?– Rakesh
Sep 7 '18 at 8:10