Groupby and print capabilities
This commit is contained in:
@@ -1,3 +1,8 @@
|
|||||||
# MORG Stream Library
|
# MORG Stream Library
|
||||||
|
|
||||||
This python library allows for the handling of data in a stream format.
|
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
|
||||||
|
```
|
||||||
@@ -15,6 +15,7 @@
|
|||||||
# You should have received a copy of the GNU General Public License
|
# You should have received a copy of the GNU General Public License
|
||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# 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
|
from typing import Any, Callable, Iterable, Iterator, Self, TypeVar, Generic
|
||||||
|
|
||||||
T = TypeVar('T')
|
T = TypeVar('T')
|
||||||
@@ -47,5 +48,14 @@ class Stream(Generic[T]):
|
|||||||
def first(self, fxn: Callable[[T], bool]) -> T | None:
|
def first(self, fxn: Callable[[T], bool]) -> T | None:
|
||||||
return next(filter(fxn, self.iter), 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:
|
def to(self, fxn: Callable) -> Any:
|
||||||
return fxn(self.iter)
|
return fxn(self.iter)
|
||||||
|
|
||||||
|
def print(self, sep=","):
|
||||||
|
print(*self.iter, sep=sep)
|
||||||
Reference in New Issue
Block a user