Groupby and print capabilities

This commit is contained in:
2026-01-29 16:23:29 -06:00
parent 666f0def09
commit ade9d85650
2 changed files with 17 additions and 2 deletions

View File

@@ -1,3 +1,8 @@
# MORG Stream Library
This python library allows for the handling of data in a stream format.
The library may be installed from Avalon with:
```
pip install git+https://git.icolotl.com/morgana/morgslib
```

View File

@@ -15,6 +15,7 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from collections import defaultdict
from typing import Any, Callable, Iterable, Iterator, Self, TypeVar, Generic
T = TypeVar('T')
@@ -47,5 +48,14 @@ class Stream(Generic[T]):
def first(self, fxn: Callable[[T], bool]) -> T | None:
return next(filter(fxn, self.iter), None)
def groupby(self, fxn: Callable[[T], Tn]) -> Stream[tuple[Tn, list[T]]]:
out: defaultdict[Tn, list[T]] = defaultdict(list)
for item in self.iter:
out[fxn(item)].append(item)
return Stream(out.items())
def to(self, fxn: Callable) -> Any:
return fxn(self.iter)
def print(self, sep=","):
print(*self.iter, sep=sep)