From a1f4605d8bd969f531365c1b746bcb094de54966 Mon Sep 17 00:00:00 2001 From: monoid Date: Wed, 23 Feb 2022 20:24:35 +0900 Subject: [PATCH] feat: groupby_index --- groupby_index.py | 36 ++++++++++++++++++++++++++++++++++++ groupby_index.test.py | 9 +++++++++ 2 files changed, 45 insertions(+) create mode 100644 groupby_index.py create mode 100644 groupby_index.test.py diff --git a/groupby_index.py b/groupby_index.py new file mode 100644 index 0000000..0c37a6d --- /dev/null +++ b/groupby_index.py @@ -0,0 +1,36 @@ +import itertools +from typing import Tuple, TypeVar, Iterable + +T = TypeVar('T') + +def groupby_index(iter: Iterable[T],n:int) -> Iterable[Iterable[T]]: + """group list by index + + Args: + iter (Iterable[T]): iterator to group by index + n (int): The size of groups + + Returns: + Iterable[Iterable[T]]: iterable object to group by index + + >>> [*map(lambda x:[*x],groupby_index([1,2,3,4],2))] + [[1, 2], [3, 4]] + """ + def keyfunc(x: Tuple[int,T]) -> int: + k, _ = x + return (k // n) + def mapper(x: Tuple[int, Tuple[int, T]]): + _, v = x + return map(lambda y: y[1],v) + g = itertools.groupby(enumerate(iter), keyfunc) + return map(mapper,g) + +if __name__ == "__main__": + test_list = [*range(20,-10,-1)] + for g in groupby_index(test_list,4): + print([*g]) + print("===") + print([*map(lambda x:[*x],groupby_index([1,2,3,4],2))]) + for g in groupby_index([1,2,3,4],2): + print([*g]) + \ No newline at end of file diff --git a/groupby_index.test.py b/groupby_index.test.py new file mode 100644 index 0000000..bd79794 --- /dev/null +++ b/groupby_index.test.py @@ -0,0 +1,9 @@ +import unittest +from groupby_index import * + +class Test(unittest.TestCase): + def test_padding_array(self): + self.assertEqual([*map(lambda x:[*x],groupby_index([1,2,3,4],2))],[[1,2],[3,4]]) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file