Collection Operations

Utility functions to operator list, tuple, and set.

List of APIs

calcpy.groupby(values, by)[source]

Partition values into several groups, and return a dict.

Parameters:
  • values (iterable)

  • by (callable) – The function to get the group of a value.

Returns:

groups (dict[hashable, list])

Raises:

TypeError – Raises when a return value of by() is not hashable.

Examples

>>> groupby(range(10), lambda x: x % 3)
{0: [0, 3, 6, 9], 1: [1, 4, 7], 2: [2, 5, 8]}
>>> groupby([0, "", False, float('nan'), "Hello"], by=bool)
{False: [0, '', False], True: [nan, 'Hello']}
calcpy.partition(values, by, count=None)[source]

Partition values into several groups, and return lists.

Parameters:
  • values (iterable)

  • by (callable) – Function to get the group index of a value. Its return value will be wrapped by int().

  • count (int, Optional) – Number of groups.

Return type:

results (list[list])

Examples

>>> partition(range(10), by=lambda x: x % 3)
[[0, 3, 6, 9], [1, 4, 7], [2, 5, 8]]

Specify the number of groups.

>>> partition([0, "", False, float('nan'), "Hello"], by=bool, count=3)
[[0, '', False], [nan, 'Hello'], []]

Raise error when the group index exceeds range.

>>> partition([-1, 1], by=int)
Traceback (most recent call last):
...
ValueError: Group index should be >= 0.
calcpy.concat(*args, key=None)[source]

Concat multiple parameters.

Parameters:
  • *args

  • key (callable)

Examples

>>> concat([1, 2, 3], [], [4, 5], [5])
[1, 2, 3, 4, 5, 5]
>>> concat((1, 2, 3), (), (4, 5), (5,))
(1, 2, 3, 4, 5, 5)
>>> concat({1, 2, 3}, set(), {4, 5}, {5})
{1, 2, 3, 4, 5}
>>> concat({1: 'a', 2: 'b'}, {}, {3: 'c', 4: 'd'}, {5: 'e'})
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
>>> import pandas as pd
>>> s = pd.Series([0, 1])
>>> concat(s, s)
0    0
1    1
0    0
1    1
dtype: int64
calcpy.convert_nested_dict_to_nested_list(data, /, maxdepth=inf)[source]

Convert a nested dictionary to a nested list.

Parameters:
  • data (dict) – Nested dictionary to convert.

  • maxdepth (int) – Maximum depth to convert to a nested list.

Returns:

A nested list representation of the nested dictionary.

Return type:

list

Example

>>> data = {"A": {"B": 1, "C": 2}, "D": {"E": 3, "F": 4}}
>>> convert_nested_dict_to_nested_list(data)
[['A', 'B', 1], ['A', 'C', 2], ['D', 'E', 3], ['D', 'F', 4]]