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()]) ?

– Rakesh
Sep 7 '18 at 8:10


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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế