LANGUAGE » PYTHON » PACKAGE
Collections
Usage
Named tuple
python
from collections import namedtupleFirst create a Class-like object with the desired fields:
python
QueryResult = namedtuple('QueryResult', ['id', 'name', 'status'])Create instances and use it:
python
tom = QueryResult(id=1, name='Tom', status='active')
tom.idThere is no way to update an instance of a namedtuple, but it is possible to create a copy with only some fields replaced:
python
inactive_tom = tom._replace(status='inactive')Counter
To count the number of occurrences of an element, use collections.Counter.
python
from collections import CounterUseful, for example, to check if two lists have the same elements regardless of order:
python
Counter(list1) == Counter(list2)