Groups elements of an iterable based on a provided function. Parameters: - arr (Iterable): The iterable to be grouped. - fn (Callable): The function to determine the grouping. - values (bool): If True, returns the values of the group. Defaults to False.
(arr: Iterable, fn: Callable, values: bool = False)
| 444 | |
| 445 | @staticmethod |
| 446 | def group(arr: Iterable, fn: Callable, values: bool = False) -> Iterable: |
| 447 | """ |
| 448 | Groups elements of an iterable based on a provided function. |
| 449 | |
| 450 | Parameters: |
| 451 | - arr (Iterable): The iterable to be grouped. |
| 452 | - fn (Callable): The function to determine the grouping. |
| 453 | - values (bool): If True, returns the values of the group. Defaults to False. |
| 454 | |
| 455 | Returns: |
| 456 | Iterable: An iterable of grouped elements. |
| 457 | """ |
| 458 | res = collections.defaultdict(list) |
| 459 | for ob in arr: |
| 460 | try: |
| 461 | hashable_dict = tuple( |
| 462 | ( |
| 463 | key, |
| 464 | tuple(value) |
| 465 | if isinstance(value, collections.abc.Iterable) |
| 466 | else value, |
| 467 | ) |
| 468 | for key, value in sorted(fn(ob).items()) |
| 469 | ) |
| 470 | res[hashable_dict].append(ob) |
| 471 | except TypeError: |
| 472 | res[fn(ob)].append(ob) |
| 473 | if not values: |
| 474 | return res |
| 475 | return res.values() |
| 476 | |
| 477 | @staticmethod |
| 478 | def get_chunks(_iter, n: int = 0, fn=None): |
no outgoing calls
no test coverage detected