Understanding Python Data Types
8.1. datetime - Basic date and time types
8.2. calendar - General calendar-related functions
8.3. collections - Container datatypes
8.4. collections.abc - Abstract Base Classes for Containers
8.5. heapq - Heap queue algorithm
8.6. bisect - Array bisection algorithm
8.7. array - Efficient arrays of numeric values
8.8. weakref - Weak references
8.9. types - Dynamic type creation and names for built-in types
8.10. copy - Shallow and deep copy operations
8.11. pprint - Data pretty printer
8.12. reprlib - Alternate repr() implementation
8.13. enum - Support for enumerations
8.2. calendar - General calendar-related functions
import calendar
>>>
print calendar.TextCalendar(firstweekday=6).formatyear(2015)
Weekday gives the day number for the given date (0-Monday, 1- Tuesday... and so on)
print(calendar.weekday(year, month, day))
Calendar.day_name - Array storing the name to item mapping for the day name
print(calendar.day_name[calendar.weekday(year, month, day)].upper())
8.3 collections
This module implements specialized container datatypes providing alternatives to Python's general purpose built-in containers, dict, list, set, andtuple.
| namedtuple() | factory function for creating tuple subclasses with named fields |
|---|---|
| deque | list-like container with fast appends and pops on either end |
| ChainMap | dict-like class for creating a single view of multiple mappings |
| Counter | dict subclass for counting hashable objects |
| OrderedDict | dict subclass that remembers the order entries were added |
| defaultdict | dict subclass that calls a factory function to supply missing values |
| UserDict | wrapper around dictionary objects for easier dict subclassing |
| UserList | wrapper around list objects for easier list subclassing |
| UserString | wrapper around string objects for easier string subclassing |
collections.Counter()
A counter is a container that stores elements as dictionary keys, and their counts are stored as dictionary values.
from collections import Counter
>>>
myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3]
print Counter(myList)
Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1})
>>>
print Counter(myList).items()
[(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)]
>>>
print Counter(myList).keys()
[1, 2, 3, 4, 5]
>>>
print Counter(myList).values()
[3, 4, 4, 2, 1]
If we want to know the 10 most common numbers, theCounter()instance also has amost_commonmethod that is very handy.
Count unique values in a list can be done more efficiently usingCounter() from [collections](https://docs.python.org/3.8/library/collections.html)
num_counts2 = Counter(a_long_list).
It is about 10 times faster than the dict version with incrementing counts
collections.OrderedDict()
Standard Python dictionaries don't keep track of the order in which keys and values are added; they only preserve the association between each key and its value.