BitPost : Heard about collections in Python?
This python module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple. My personal favorite is collections.Counter. It returns count dictionary of hashable input or mapping. The elements of hashable input are ‘key’ and their count is ‘value’. It makes our lives so easy and I “count” it as one of the reasons why I love Python. Let’s say my call history is as follows,
Call_List = [ Jack, Jill, Humpty, Jill, Jack, Mickey, Jill ]
Now I want to count how many times I called every person. How will you do? Looping and updating counter variable? No need, it can be done in 2 lines.
>>>C = Counter ()>>>Print(C(Call_List)) Counter({Jack : 2, Jill : 3, Humpty : 1, Mickey : 1})
Also I can find the most called person easily without looping and manually coding for that.
>>>C.most_common(1) [ (Jill, 3) ] >>>C.most_common(2) [ (Jill, 3), (Jack ,2) ]
I can even add, subtract two counter objects. There are other cool stuff included in collections module like deque, defaultDict, orderedDict and more. Go check them out for yourself here https://lnkd.in/fU8JE87
Follow #LearnWithAkansha on LinkedIn for more knowledgeable updates. You can follow me on Twitter, my work on Github, and connect professionally with me on LinkedIn.