Python : collections module
Python has general purpose data types like dict, list, set, tuple. Collections module has following additional useful datatype
1. namedtuple
Useful to contruct objects
2. Counter
It works with string, list, and sentence. Sentence should be split with ' ' to convert into list of words.
suppose
c = Counter(list)
then
c.values() gives only count. So sum(c.values()) givestotal of all counts
c.most_common() sort based on frequency and return list of tuples
c.most_common()[0][0] gives the item with maximum occurance
c.most_common()[:-2:-1] gives the item with maximum occurance
c.most_common()[:-n-1:-1] gives the item with n least common elements
c.substract(d) Here is d is another Counter. The result will be frequency for each element will be substraced as per its frequency in d.
3. defaultdict(object)
It gives default empty dictionary.
4. OrderedDict
OrderedDict(sorted(d.items(), key=lambda t: t[0])) to sort with key
OrderedDict(sorted(d.items(), key=lambda t: t[1])) to sort with value
5. deque
To add : append(), appendleft()
To remove : pop() , popleft()
to count: count()
To insert as specific index i : insert(i, x)
6. ChainMap
This is to join 2 dict as a list with 2 elements as dict
1. namedtuple
Useful to contruct objects
2. Counter
It works with string, list, and sentence. Sentence should be split with ' ' to convert into list of words.
suppose
c = Counter(list)
then
c.values() gives only count. So sum(c.values()) givestotal of all counts
c.most_common() sort based on frequency and return list of tuples
c.most_common()[0][0] gives the item with maximum occurance
c.most_common()[:-2:-1] gives the item with maximum occurance
c.most_common()[:-n-1:-1] gives the item with n least common elements
c.substract(d) Here is d is another Counter. The result will be frequency for each element will be substraced as per its frequency in d.
3. defaultdict(object)
It gives default empty dictionary.
4. OrderedDict
OrderedDict(sorted(d.items(), key=lambda t: t[0])) to sort with key
OrderedDict(sorted(d.items(), key=lambda t: t[1])) to sort with value
5. deque
To add : append(), appendleft()
To remove : pop() , popleft()
to count: count()
To insert as specific index i : insert(i, x)
6. ChainMap
This is to join 2 dict as a list with 2 elements as dict
0 comments:
Post a Comment