utils¶
- pyshortio.utils.take(n, iterable)[source]¶
Return first n items of the iterable as a list.
>>> take(3, range(10)) [0, 1, 2]
If there are fewer than n items in the iterable, all of them are returned.
>>> take(10, range(3)) [0, 1, 2]
- pyshortio.utils.chunked(iterable, n, strict=False)[source]¶
Break iterable into lists of length n:
>>> list(chunked([1, 2, 3, 4, 5, 6], 3)) [[1, 2, 3], [4, 5, 6]]
By the default, the last yielded list will have fewer than n elements if the length of iterable is not divisible by n:
>>> list(chunked([1, 2, 3, 4, 5, 6, 7, 8], 3)) [[1, 2, 3], [4, 5, 6], [7, 8]]
To use a fill-in value instead, see the
grouper()recipe.If the length of iterable is not divisible by n and strict is
True, thenValueErrorwill be raised before the last list is yielded.
- pyshortio.utils.group_by(iterable: Iterable[VT], get_key: Callable[[VT], KT]) Dict[KT, List[VT]][source]¶
Group items by it’s key, with type hint.
Example:
>>> class Record: ... def __init__(self, product: str, date: str, sale: int): ... self.product = product ... self.date = date ... self.sale = sale >>> records = [ ... Record("apple", "2020-01-01", 10), ... Record("apple", "2020-01-02", 20), ... Record("apple", "2020-01-03", 30), ... Record("banana", "2020-01-01", 10), ... Record("banana", "2020-01-02", 20), ... Record("banana", "2020-01-03", 30), ... ] >>> group_by(records, lambda x: x.product) { "apple": [ Record("apple", "2020-01-01", 10), Record("apple", "2020-01-02", 20), Record("apple", "2020-01-03", 30), ], "banana": [ Record("banana", "2020-01-01", 10), Record("banana", "2020-01-02", 20), Record("banana", "2020-01-03", 30), ], }