py_operations¶
shortfx.fxPython.py_operations
¶
shortfx - fxPython: Python Operations Module
This module provides advanced utility functions for Python data structure operations. It includes functions for: - JSON manipulation and merging - List, tuple, and set operations (unique, flatten, intersection) - Dictionary operations and filtering - Subsequence and sublist checking - Collection filtering and merging - Command execution and expression evaluation - Interactive user selection from collections
All functions follow PEP standards with complete documentation including complexity analysis.
Functions¶
add_to_tuple(p_tuple: Tuple[Any, ...], p_value: Any) -> Tuple[Any, ...]
¶
Adds an element to the end of a tuple.
Since tuples are immutable, this function creates and returns a new tuple that contains all elements from the original tuple plus the new value appended to the end.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p_tuple
|
Tuple[Any, ...]
|
The original tuple to which the element will be added. |
required |
p_value
|
Any
|
The new value to append to the tuple. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[Any, ...]
|
Tuple[Any, ...]: A new tuple with the value appended at the end. |
Example of use
add_to_tuple((1, 2), 3) (1, 2, 3) add_to_tuple((), "hello") ('hello',)
Cost: O(n), where n is the number of elements in the tuple.
Source code in shortfx/fxPython/py_operations.py
calculate(expression_string)
¶
Evaluates a compound arithmetic expression from a string.
Handles implicit multiplication (e.g. 3(4+2) → 3*(4+2)), then
delegates to :func:~shortfx.fxNumeric.calculator_functions.evaluate_expression
for safe AST-based evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expression_string
|
str
|
The mathematical expression to be evaluated. |
required |
Returns:
| Type | Description |
|---|---|
|
int | float: The numerical result of the expression. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the expression is syntactically incorrect or invalid. |
Example of use
calculate("3 + 4 * 5") 23 calculate("2 * 3(6 / 2) - 9 + 6") 15.0
Cost: O(n) where n is the expression length.
Source code in shortfx/fxPython/py_operations.py
choose(index: int, *values: Any) -> Any
¶
Chooses a value from a list of values based on a 1-based index.
Description
Returns the value at the given position (1-based). Equivalent to Excel CHOOSE.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
The 1-based position to select. |
required |
*values
|
Any
|
The values to choose from. |
()
|
Returns:
| Type | Description |
|---|---|
Any
|
The value at the specified index. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If index is out of range or no values are provided. |
TypeError
|
If index is not an integer. |
Example
choose(2, "a", "b", "c") 'b' choose(1, 10, 20, 30) 10
Cost: O(1)
Source code in shortfx/fxPython/py_operations.py
choose_cols(array: list[list[Any]], *col_nums: int) -> list[list[Any]]
¶
Selects specific columns from a 2-D array.
Description
Returns a new array containing only the columns at the given 1-based positions. Negative indices count from the right. Equivalent to Excel CHOOSECOLS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
list[list[Any]]
|
A 2-D list. |
required |
*col_nums
|
int
|
1-based column indices (negative = from right). |
()
|
Returns:
| Type | Description |
|---|---|
list[list[Any]]
|
list[list[Any]]: Array with selected columns only. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If any column index is out of bounds. |
Example
choose_cols([[1, 2, 3], [4, 5, 6]], 1, 3) [[1, 3], [4, 6]] choose_cols([[1, 2, 3]], -1) [[3]]
Complexity: O(rows × selected_cols)
Source code in shortfx/fxPython/py_operations.py
choose_rows(array: list[list[Any]], *row_nums: int) -> list[list[Any]]
¶
Selects specific rows from a 2-D array.
Description
Returns a new array containing only the rows at the given 1-based positions. Negative indices count from the bottom. Equivalent to Excel CHOOSEROWS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
list[list[Any]]
|
A 2-D list. |
required |
*row_nums
|
int
|
1-based row indices (negative = from bottom). |
()
|
Returns:
| Type | Description |
|---|---|
list[list[Any]]
|
list[list[Any]]: Array with selected rows only. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If any row index is out of bounds. |
Example
choose_rows([[1, 2], [3, 4], [5, 6]], 1, 3) [[1, 2], [5, 6]] choose_rows([[1, 2], [3, 4]], -1) [[3, 4]]
Complexity: O(selected_rows × cols)
Source code in shortfx/fxPython/py_operations.py
chunk(iterable: Iterable, n: int) -> List[list]
¶
Splits an iterable into fixed-size chunks.
The last chunk may contain fewer than n elements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
iterable
|
Iterable
|
The input iterable to split. |
required |
n
|
int
|
Size of each chunk. Must be >= 1. |
required |
Returns:
| Type | Description |
|---|---|
List[list]
|
A list of lists, each containing up to n elements. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If iterable is not iterable or n is not int. |
ValueError
|
If n < 1. |
Example
chunk([1, 2, 3, 4, 5], 2) [[1, 2], [3, 4], [5]] chunk("abcdef", 3) [['a', 'b', 'c'], ['d', 'e', 'f']] chunk(range(7), 4) [[0, 1, 2, 3], [4, 5, 6]]
Cost: O(n) where n is the number of elements.
Source code in shortfx/fxPython/py_operations.py
collection_avg(collection: Iterable[Union[int, float]], ignore_none: bool = True) -> Optional[float]
¶
Calculates the average of the numeric values in an iterable collection.
This function is equivalent to the SQL aggregate function AVG and allows calculating the average of numeric values in any iterable collection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
collection
|
Iterable[Union[int, float]]
|
Collection of numeric values. |
required |
ignore_none
|
bool
|
If True, ignores None values in the calculation. Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
Optional[float]
|
Optional[float]: The average of the values, or None if the collection is empty or contains no valid values. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the collection is not iterable or contains non-numeric values. |
Example of use
collection_avg([1, 2, 3, 4, 5]) 3.0 collection_avg([10, 20, None, 30], ignore_none=True) 20.0 collection_avg((5.5, 10.5, 15.5)) 10.5
Cost: O(n), where n is the number of elements in the collection.
Source code in shortfx/fxPython/py_operations.py
collection_count(collection: Iterable[Any], ignore_none: bool = True) -> int
¶
Counts the number of elements in an iterable collection.
This function is equivalent to the SQL aggregate function COUNT and allows counting elements in any iterable collection, with an option to ignore None values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
collection
|
Iterable[Any]
|
The collection to count. |
required |
ignore_none
|
bool
|
If True, does not count None values. Defaults to True (similar to COUNT(field) in SQL). |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of elements in the collection. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the argument is not an iterable. |
Example of use
collection_count([1, 2, 3, 4, 5]) 5 collection_count([1, None, 3, None, 5], ignore_none=True) 3 collection_count([1, None, 3, None, 5], ignore_none=False) 5
Cost: O(n), where n is the number of elements in the collection.
Source code in shortfx/fxPython/py_operations.py
collection_filter(collection: Iterable[Any], filter_logic_func: Callable[[Any], bool]) -> Union[List[Any], Tuple[Any, ...], Set[Any]]
¶
Filters an iterable (list, tuple, set, etc.) based on a provided filtering function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
collection
|
Iterable[Any]
|
The iterable to filter (e.g., a list, tuple, or set). |
required |
filter_logic_func
|
Callable[[Any], bool]
|
A callable (function) that takes a single item from the collection as input and returns True if the item should be included in the filtered result, False otherwise. |
required |
Returns:
| Type | Description |
|---|---|
Union[List[Any], Tuple[Any, ...], Set[Any]]
|
A new collection of the same type as the input (list, tuple, or set) |
Union[List[Any], Tuple[Any, ...], Set[Any]]
|
containing only the items for which filter_logic_func returned True. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If 'collection' is not an iterable or 'filter_logic_func' is not callable. |
Example of use
numbers = [1, 2, 3, 4, 5, 6] is_even = lambda x: x % 2 == 0 collection_filter(numbers, is_even) [2, 4, 6]
data_tuple = (10, 15, 20, 25) is_greater_than_20 = lambda x: x > 20 collection_filter(data_tuple, is_greater_than_20) (25,)
unique_letters = {'a', 'b', 'c', 'd'} is_vowel = lambda x: x in 'aeiou' collection_filter(unique_letters, is_vowel)
Source code in shortfx/fxPython/py_operations.py
collection_max(collection: Iterable[Any], ignore_none: bool = True) -> Optional[Any]
¶
Returns the highest value in an iterable collection.
This function is equivalent to the SQL aggregate function MAX and allows finding the maximum value in any iterable collection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
collection
|
Iterable[Any]
|
The collection to search for the maximum. |
required |
ignore_none
|
bool
|
If True, ignores None values in the calculation. Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
Optional[Any]
|
Optional[Any]: The maximum value in the collection, or None if it is empty or contains only None. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the collection is not iterable. |
ValueError
|
If the collection is empty after filtering None. |
Example of use
collection_max([1, 5, 3, 9, 2]) 9 collection_max(['apple', 'zebra', 'banana']) 'zebra' collection_max([1.5, None, 3.7, 2.1], ignore_none=True) 3.7
Cost: O(n), where n is the number of elements in the collection.
Source code in shortfx/fxPython/py_operations.py
collection_min(collection: Iterable[Any], ignore_none: bool = True) -> Optional[Any]
¶
Returns the smallest value in an iterable collection.
This function is equivalent to the SQL aggregate function MIN and allows finding the minimum value in any iterable collection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
collection
|
Iterable[Any]
|
The collection to search for the minimum. |
required |
ignore_none
|
bool
|
If True, ignores None values in the calculation. Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
Optional[Any]
|
Optional[Any]: The minimum value in the collection, or None if it is empty or contains only None. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the collection is not iterable. |
ValueError
|
If the collection is empty after filtering None. |
Example of use
collection_min([5, 1, 9, 3, 2]) 1 collection_min(['zebra', 'apple', 'banana']) 'apple' collection_min([3.7, None, 1.5, 2.1], ignore_none=True) 1.5
Cost: O(n), where n is the number of elements in the collection.
Source code in shortfx/fxPython/py_operations.py
collection_stdev(collection: Iterable[Union[int, float]], is_sample: bool = True, ignore_none: bool = True) -> Optional[float]
¶
Calculates the standard deviation of the values in an iterable collection.
This function is equivalent to the SQL aggregate functions STDEV (sample) and STDEVP (population), allowing the calculation of standard deviation in any iterable collection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
collection
|
Iterable[Union[int, float]]
|
Collection of numeric values. |
required |
is_sample
|
bool
|
If True, calculates for a sample (n-1). If False, calculates for a population (n). Defaults to True (equivalent to SQL's STDEV). |
True
|
ignore_none
|
bool
|
If True, ignores None values in the calculation. Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
Optional[float]
|
Optional[float]: The standard deviation, or None if there is not enough data. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the collection is not iterable or contains non-numeric values. |
ValueError
|
If there are fewer than 2 values for a sample calculation. |
Example of use
collection_stdev([2, 4, 4, 4, 5, 5, 7, 9]) 2.138089935299395 collection_stdev([2, 4, 4, 4, 5, 5, 7, 9], is_sample=False) 2.0 collection_stdev([10, None, 20, 30], ignore_none=True) 10.0
Cost: O(n), where n is the number of elements in the collection.
Source code in shortfx/fxPython/py_operations.py
collection_sum(collection: Iterable[Union[int, float]], ignore_none: bool = True) -> Union[int, float]
¶
Calculates the sum of the numeric values in an iterable collection.
This function is equivalent to the SQL aggregate function SUM and allows summing numeric values in any iterable collection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
collection
|
Iterable[Union[int, float]]
|
Collection of numeric values. |
required |
ignore_none
|
bool
|
If True, ignores None values in the calculation. Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
Union[int, float]
|
Union[int, float]: The sum of the values. Returns 0 if the collection is empty. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the collection is not iterable or contains non-numeric values. |
Example of use
collection_sum([1, 2, 3, 4, 5]) 15 collection_sum([10, None, 20, 30], ignore_none=True) 60 collection_sum((5.5, 10.5, 15.5)) 31.5
Cost: O(n), where n is the number of elements in the collection.
Source code in shortfx/fxPython/py_operations.py
combine_dictionaries(dict_one: dict, dict_two: dict, operation: str) -> dict
¶
Performs union or intersection operations on two dictionaries.
This function takes two dictionaries and an operation type ('union' or 'intersection') to return a new dictionary based on the specified operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dict_one
|
dict
|
The first dictionary. |
required |
dict_two
|
dict
|
The second dictionary. |
required |
operation
|
str
|
The type of operation to perform. Must be 'union' or 'intersection'. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
A new dictionary resulting from the specified operation. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an unsupported operation type is provided. |
Example of use
dict_a = {'a': 1, 'b': 2, 'c': 3} dict_b = {'b': 4, 'd': 5}
union_result = combine_dictionaries(dict_a, dict_b, 'union')
Expected:¶
intersection_result = combine_dictionaries(dict_a, dict_b, 'intersection')
Expected:¶
Cost
O(N + M) for union (where N and M are the number of items in dict_one and dict_two respectively) O(min(N, M)) for intersection (iterating over the smaller dictionary's keys)
Source code in shortfx/fxPython/py_operations.py
conditional_average(values: List[Union[int, float]], criteria: Callable[[Union[int, float]], bool]) -> float
¶
Averages values that match a criteria function.
Description
Computes the arithmetic mean of values for which the criteria function returns True. Equivalent to Excel AVERAGEIF logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
List[Union[int, float]]
|
A list of numeric values. |
required |
criteria
|
Callable[[Union[int, float]], bool]
|
A callable that takes a value and returns True/False. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The average of matching values. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no values match the criteria. |
Example
conditional_average([1, 2, 3, 4, 5], lambda x: x > 2) 4.0 conditional_average([10, 20, 30], lambda x: x >= 20) 25.0
Cost: O(n)
Source code in shortfx/fxPython/py_operations.py
conditional_count(values: List[Any], criteria: Callable[[Any], bool]) -> int
¶
Counts values that match a criteria function.
Description
Iterates over the values and counts those for which the criteria function returns True. Equivalent to Excel COUNTIF logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
List[Any]
|
A list of values. |
required |
criteria
|
Callable[[Any], bool]
|
A callable that takes a value and returns True/False. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The count of matching values. |
Example
conditional_count([1, 2, 3, 4, 5], lambda x: x > 3) 2 conditional_count(["a", "b", "a"], lambda x: x == "a") 2
Cost: O(n)
Source code in shortfx/fxPython/py_operations.py
conditional_max(values: List[Union[int, float]], criteria: Callable[[Union[int, float]], bool]) -> Union[int, float]
¶
Returns the maximum of values that match a criteria function.
Description
Finds the largest value for which the criteria function returns True. Equivalent to Excel MAXIFS logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
List[Union[int, float]]
|
A list of numeric values. |
required |
criteria
|
Callable[[Union[int, float]], bool]
|
A callable that takes a value and returns True/False. |
required |
Returns:
| Type | Description |
|---|---|
Union[int, float]
|
The maximum matching value. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no values match the criteria. |
Example
conditional_max([1, 2, 3, 4, 5], lambda x: x <= 3) 3 conditional_max([10, 20, 30], lambda x: x < 25) 20
Cost: O(n)
Source code in shortfx/fxPython/py_operations.py
conditional_min(values: List[Union[int, float]], criteria: Callable[[Union[int, float]], bool]) -> Union[int, float]
¶
Returns the minimum of values that match a criteria function.
Description
Finds the smallest value for which the criteria function returns True. Equivalent to Excel MINIFS logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
List[Union[int, float]]
|
A list of numeric values. |
required |
criteria
|
Callable[[Union[int, float]], bool]
|
A callable that takes a value and returns True/False. |
required |
Returns:
| Type | Description |
|---|---|
Union[int, float]
|
The minimum matching value. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no values match the criteria. |
Example
conditional_min([1, 2, 3, 4, 5], lambda x: x > 2) 3 conditional_min([10, 20, 30], lambda x: x >= 20) 20
Cost: O(n)
Source code in shortfx/fxPython/py_operations.py
conditional_sum(values: List[Union[int, float]], criteria: Callable[[Union[int, float]], bool]) -> float
¶
Sums values that match a criteria function.
Description
Iterates over the values and sums only those for which the criteria function returns True. Equivalent to Excel SUMIF logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
List[Union[int, float]]
|
A list of numeric values. |
required |
criteria
|
Callable[[Union[int, float]], bool]
|
A callable that takes a value and returns True/False. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The sum of matching values. |
Example
conditional_sum([1, 2, 3, 4, 5], lambda x: x > 3) 9 conditional_sum([10, 20, 30], lambda x: x < 15) 10
Cost: O(n)
Source code in shortfx/fxPython/py_operations.py
count_blank(values: list) -> int
¶
Count blank items (None or "").
Equivalent to the Excel COUNTBLANK function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
list
|
List of values to inspect. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of blank items. |
Example
count_blank([1, "", None, "hello", 0]) 2
Complexity: O(n)
Source code in shortfx/fxPython/py_operations.py
count_by(iterable: Iterable[Any], key_func: Callable[[Any], Any]) -> dict
¶
Count the number of elements in each group defined by a key function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
iterable
|
Iterable[Any]
|
Input iterable. |
required |
key_func
|
Callable[[Any], Any]
|
Function returning the grouping key. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dict mapping each key to its count. |
Example
count_by(['apple', 'ant', 'banana', 'avocado'], lambda s: s[0])
Complexity: O(n)
Source code in shortfx/fxPython/py_operations.py
count_if(values: list, criteria) -> int
¶
Count items that meet an Excel-style criteria.
Equivalent to the Excel COUNTIF function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
list
|
List of values to evaluate. |
required |
criteria
|
Excel-style criteria (e.g. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of matching items. |
Example
count_if([1, 5, 10, 15, 20], ">8") 3 count_if(["a", "b", "a", "c"], "a") 2
Complexity: O(n)
Source code in shortfx/fxPython/py_operations.py
count_ifs(values: list, *criteria_pairs) -> int
¶
Count items where every criteria pair is satisfied.
Equivalent to the Excel COUNTIFS function. Criteria pairs are
given as alternating (range, criteria) arguments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
list
|
Primary range whose length determines the row count. |
required |
*criteria_pairs
|
Alternating |
()
|
Returns:
| Type | Description |
|---|---|
int
|
Number of indices where all criteria are met. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If criteria_pairs length is odd or ranges differ in length. |
Example
count_ifs( ... [1, 2, 3, 4, 5], ... [1, 2, 3, 4, 5], ">1", ... [1, 2, 3, 4, 5], "<5", ... ) 3
Complexity: O(n * k) where k is the number of criteria pairs.
Source code in shortfx/fxPython/py_operations.py
count_numbers(*values) -> int
¶
Count how many items are numeric (int or float, excluding bool).
Equivalent to the Excel COUNT function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*values
|
Individual values or lists/tuples of values. |
()
|
Returns:
| Type | Description |
|---|---|
int
|
Number of numeric items. |
Example
count_numbers([1, "a", 2, None, 3.5]) 3
Complexity: O(n)
Source code in shortfx/fxPython/py_operations.py
count_values(*values) -> int
¶
Count non-empty, non-None items.
Equivalent to the Excel COUNTA function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*values
|
Individual values or lists/tuples of values. |
()
|
Returns:
| Type | Description |
|---|---|
int
|
Number of non-blank items. |
Example
count_values([1, "", None, "hello", 0]) 3
Complexity: O(n)
Source code in shortfx/fxPython/py_operations.py
deep_flatten(nested: Any) -> list
¶
Recursively flatten a nested structure of arbitrary depth.
Unlike :func:flatten_list which flattens one level, this function
handles any nesting depth. Strings are not expanded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nested
|
Any
|
Nested lists/tuples/iterables. |
required |
Returns:
| Type | Description |
|---|---|
list
|
Flat list of all leaf elements. |
Example
deep_flatten([1, [2, [3, [4]], 5]]) [1, 2, 3, 4, 5] deep_flatten([[1, 2], 'hello', [3, [4]]]) [1, 2, 'hello', 3, 4]
Complexity: O(n) total elements
Source code in shortfx/fxPython/py_operations.py
deep_merge(dict1: dict, dict2: dict) -> dict
¶
Recursively merges two dictionaries.
Nested dicts are merged instead of overwritten. For non-dict values, dict2 takes precedence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dict1
|
dict
|
The base dictionary. |
required |
dict2
|
dict
|
The dictionary whose values override dict1. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
A new merged dictionary. Original inputs are not mutated. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If either argument is not a dict. |
Example
deep_merge({"a": 1, "b": {"x": 10}}, {"b": {"y": 20}, "c": 3}) {'a': 1, 'b': {'x': 10, 'y': 20}, 'c': 3} deep_merge({"a": 1}, {"a": 2})
Cost: O(n) where n is the total number of keys across both dicts.
Source code in shortfx/fxPython/py_operations.py
dictionary_filter_by_keys(input_dict: dict, keys_to_include: list) -> dict
¶
Filters a dictionary, returning a new dictionary with only the specified keys.
This function iterates through a provided list of keys and creates a new dictionary containing only the key-value pairs where the key exists in the original dictionary. This is highly useful for preparing a subset of data for serialization or other processing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_dict
|
dict
|
The original dictionary to filter. |
required |
keys_to_include
|
list
|
A list of keys (strings) that should be included in the new, filtered dictionary. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
A new dictionary containing only the key-value pairs
corresponding to the |
Raises:
| Type | Description |
|---|---|
TypeError
|
If input_dict is not a dictionary or keys_to_include is not a list. |
Example
dictionary_filter_by_keys({"name": "Charlie", "age": 45, "city": "London"}, ["name", "city", "country"])
Source code in shortfx/fxPython/py_operations.py
dictionary_rename_keys(original_dict: dict, key_mapping: dict) -> dict
¶
Renames keys in a dictionary based on a provided mapping.
This function iterates through the original dictionary's items. If a key
exists in the key_mapping, its corresponding value from the mapping is
used as the new key in the new dictionary. Keys not found in the mapping
are kept as is. This approach creates a new dictionary, leaving the
original dictionary unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_dict
|
dict
|
The dictionary whose keys are to be renamed. |
required |
key_mapping
|
dict
|
A dictionary where keys are old key names and values are the new key names. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
A new dictionary with the keys renamed according to the |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Example of use
my_dict = {"name": "Alice", "age": 30} mapping = {"name": "full_name", "age": "person_age"} renamed_dict = dictionary_rename_keys(my_dict, mapping) print(renamed_dict)
Source code in shortfx/fxPython/py_operations.py
drop_from_array(array: list[list[Any]], rows: int = 0, columns: int = 0) -> list[list[Any]]
¶
Drops rows and/or columns from a 2-D array.
Description
If rows > 0, drops from the top; if rows < 0, drops from the bottom. Same logic for columns (left/right). Equivalent to Excel DROP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
list[list[Any]]
|
A 2-D list. |
required |
rows
|
int
|
Number of rows to drop (positive=top, negative=bottom). |
0
|
columns
|
int
|
Number of columns to drop (positive=left, negative=right). |
0
|
Returns:
| Type | Description |
|---|---|
list[list[Any]]
|
list[list[Any]]: The trimmed array. |
Example
drop_from_array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], rows=1, columns=-1) [[4, 5], [7, 8]] drop_from_array([[1, 2], [3, 4]], rows=-1) [[1, 2]]
Complexity: O(rows × cols)
Source code in shortfx/fxPython/py_operations.py
expand_array(array: list, rows: int = None, columns: int = None, pad_with: Any = None) -> list
¶
Expand a 2-D array to target dimensions, padding new cells.
Description
Pads an array with a fill value to reach the specified number of rows and columns. Equivalent to Excel EXPAND.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
list
|
2-D list to expand. |
required |
rows
|
int
|
Target row count (default: keep current). |
None
|
columns
|
int
|
Target column count (default: keep current). |
None
|
pad_with
|
Any
|
Value for new cells (default None). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
list
|
Expanded 2-D list. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If array is not a list. |
ValueError
|
If target is smaller than source. |
Example
expand_array([[1, 2], [3, 4]], 3, 4, 0) [[1, 2, 0, 0], [3, 4, 0, 0], [0, 0, 0, 0]]
Complexity: O(rows × columns)
Source code in shortfx/fxPython/py_operations.py
2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 | |
filter_elements_by_another(main_collection: Iterable, filter_criteria: Iterable, return_type: str = 'list') -> Union[list, tuple, set]
¶
Filters elements from a main collection that are also present in a filter criteria collection.
This function is highly flexible, accepting lists, tuples, or sets as input for both
main_collection and filter_criteria. It efficiently identifies common elements
and returns them in the specified output type (list, tuple, or set).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
main_collection
|
Iterable
|
The collection (list, tuple, or set) from which elements will be filtered. |
required |
filter_criteria
|
Iterable
|
The collection (list, tuple, or set) containing elements to use as a filter. |
required |
return_type
|
str
|
The desired type of the returned collection. Accepted values are "list", "tuple", or "set". Defaults to "list". |
'list'
|
Returns:
| Type | Description |
|---|---|
Union[list, tuple, set]
|
Union[list, tuple, set]: A new collection of the specified |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
Example of use
my_set = {1, 2, 3, 4, 5} filter_list = [2, 4, 6] filter_elements_by_another(my_set, filter_list, return_type="set")
data_tuple = ("a", "b", "c", "d") criteria_set = {"b", "d", "e"} filter_elements_by_another(data_tuple, criteria_set, return_type="list") ['b', 'd']
list_numbers = [10, 20, 30, 20, 40] common_values = {20, 50} filter_elements_by_another(list_numbers, common_values, return_type="tuple") (20, 20)
Source code in shortfx/fxPython/py_operations.py
find(predicate: Callable, iterable: Iterable, default: Any = None) -> Any
¶
Returns the first element matching a predicate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predicate
|
Callable
|
A callable returning True for the desired element. |
required |
iterable
|
Iterable
|
The collection to search. |
required |
default
|
Any
|
Value returned when no match is found (default None). |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The first matching element, or |
Example
find(lambda x: x > 3, [1, 2, 3, 4, 5]) 4 find(lambda x: x > 10, [1, 2, 3], default=-1) -1
Cost: O(n) worst case.
Source code in shortfx/fxPython/py_operations.py
flatten_dict(d: dict, separator: str = '.', parent_key: str = '') -> dict
¶
Flattens a nested dictionary into a single-level dictionary.
Nested keys are joined with separator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict
|
The nested dictionary to flatten. |
required |
separator
|
str
|
Separator between key levels (default "."). |
'.'
|
parent_key
|
str
|
Internal prefix (used by recursion). |
''
|
Returns:
| Type | Description |
|---|---|
dict
|
A flat dictionary with composite keys. |
Example
flatten_dict({"a": {"b": 1, "c": {"d": 2}}})
Cost: O(n) where n is total number of leaf values.
Source code in shortfx/fxPython/py_operations.py
flatten_list(p_list: list[list]) -> list
¶
Flattens a list of lists into a single, one-dimensional list.
Delegates to :func:~shortfx.fxPython.py_itertools.flatten.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p_list
|
list[list]
|
The input list of lists. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
list |
list
|
A new list containing all elements from the sublists. |
Example of use
flatten_list([[1, 2, 3], [4, 5], [6]]) [1, 2, 3, 4, 5, 6]
Cost: O(n), where n is the total number of elements across all sublists.
Source code in shortfx/fxPython/py_operations.py
frequencies(items: Iterable) -> dict
¶
Counts occurrences of each element in an iterable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
Iterable
|
The collection of hashable elements. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
A dictionary mapping each element to its count. |
Example
frequencies(["a", "b", "a", "c", "a"])
Cost: O(n)
Source code in shortfx/fxPython/py_operations.py
get_nested(data: dict, keys: List[str], default: Any = None) -> Any
¶
Retrieves a value from a nested dictionary using a sequence of keys.
Safely traverses nested dicts without raising KeyError. Returns
default if any intermediate key is missing or not a dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
The nested dictionary. |
required |
keys
|
List[str]
|
Ordered list of keys forming the path. |
required |
default
|
Any
|
Value to return if the path does not exist. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The value at the nested path, or default. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If data is not a dict or keys is not a list. |
Example
get_nested({"a": {"b": {"c": 42}}}, ["a", "b", "c"]) 42 get_nested({"a": {"b": 1}}, ["a", "x"], default=-1) -1 get_nested({}, ["a"], default="missing") 'missing'
Cost: O(k) where k is the length of keys.
Source code in shortfx/fxPython/py_operations.py
group_by(iterable: Iterable, key_func: Callable) -> dict
¶
Groups elements of an iterable by a key function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
iterable
|
Iterable
|
The collection to group. |
required |
key_func
|
Callable
|
A callable that returns the grouping key for each element. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
A dictionary mapping each key to a list of matching elements. |
Example
group_by(["apple", "avocado", "banana", "blueberry"], lambda x: x[0]) {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry']} group_by([1, 2, 3, 4, 5, 6], lambda x: x % 2)
Cost: O(n) where n is the number of elements.
Source code in shortfx/fxPython/py_operations.py
hlookup(lookup_value: Any, table: List[List[Any]], row_index: int, approximate: bool = False) -> Any
¶
Searches for a value in the first row and returns a value from another row.
Description
Looks up a value in the first row of a table (list of rows) and returns the corresponding value from the specified row index. Equivalent to Excel HLOOKUP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lookup_value
|
Any
|
The value to search for in the first row. |
required |
table
|
List[List[Any]]
|
A list of rows (lists), each with the same number of columns. |
required |
row_index
|
int
|
The 1-based row index to return (1 = first row). |
required |
approximate
|
bool
|
If True, finds the closest match less than or equal to the lookup value (first row must be sorted ascending). If False, requires an exact match. |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
The value from the matching column at the specified row. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no match is found, row_index is out of range, or table is empty. |
TypeError
|
If table is not a list of lists. |
Example
table = [["a", "b", "c"], [1, 2, 3], [4, 5, 6]] hlookup("b", table, 2) 2 hlookup(2.5, [[1, 2, 3], [10, 20, 30]], 2, approximate=True) 20
Cost: O(m) where m is the number of columns.
Source code in shortfx/fxPython/py_operations.py
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 | |
hstack(*arrays: list[list[Any]]) -> list[list[Any]]
¶
Horizontally concatenates 2-D arrays side by side.
Description
Joins multiple 2-D arrays by appending columns. All arrays must have the same number of rows. Equivalent to Excel HSTACK.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*arrays
|
list[list[Any]]
|
Two or more 2-D arrays. |
()
|
Returns:
| Type | Description |
|---|---|
list[list[Any]]
|
list[list[Any]]: Combined array. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If arrays have different row counts. |
Example
hstack([[1, 2], [3, 4]], [[5], [6]]) [[1, 2, 5], [3, 4, 6]]
Complexity: O(rows × total_cols)
Source code in shortfx/fxPython/py_operations.py
index_2d(array: list[list[Any]], row_num: int, col_num: int | None = None) -> Any
¶
Returns an element or row/column from a 2-D array.
Description
Uses 1-based indexing. If col_num is omitted, returns the entire row. If row_num is 0, returns the entire column. Equivalent to Excel INDEX.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
list[list[Any]]
|
A 2-D list (list of lists). |
required |
row_num
|
int
|
1-based row index (0 to get entire column). |
required |
col_num
|
int | None
|
1-based column index (None to get entire row). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
The element, row, or column. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If row_num or col_num is out of bounds. |
TypeError
|
If array is not a list of lists. |
Example
index_2d([[10, 20], [30, 40]], 2, 1) 30 index_2d([[10, 20], [30, 40]], 1) [10, 20]
Complexity: O(1) for element access, O(rows) for column
Source code in shortfx/fxPython/py_operations.py
index_by(dicts: List[dict], key: str) -> dict
¶
Index a list of dicts by a given field, creating a lookup table.
If multiple dicts share the same key value, the last one wins.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dicts
|
List[dict]
|
List of dictionaries. |
required |
key
|
str
|
Field name to use as the index key. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dict mapping key values to their source dicts. |
Example
data = [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}] index_by(data, 'id') {1: {'id': 1, 'name': 'Alice'}, 2: {'id': 2, 'name': 'Bob'}}
Complexity: O(n)
Source code in shortfx/fxPython/py_operations.py
is_subsequence(sub_sequence: Sequence[Hashable], main_sequence: Sequence[Hashable]) -> bool
¶
Checks if 'sub_sequence' is a subsequence of 'main_sequence', maintaining the order of elements.
This function works correctly for ordered sequence types like lists and tuples. It does not logically apply to unordered collections like sets, as the concept of "order" is not defined for them. If you need to check element presence without regard to order in sets, consider checking if one set is a subset of another.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sub_sequence
|
Sequence[Hashable]
|
The potential subsequence (e.g., a list or a tuple). |
required |
main_sequence
|
Sequence[Hashable]
|
The main sequence to check against (e.g., a list or a tuple). Elements within the sequences should be hashable for efficient searching if the underlying implementation uses hashing. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if 'sub_sequence' is a subsequence of 'main_sequence', False otherwise. |
Example
is_subsequence(["apple", "banana"], ["orange", "apple", "grape", "banana", "kiwi"]) True is_subsequence(["banana", "apple"], ["orange", "apple", "grape", "banana", "kiwi"]) False is_subsequence((1, 3), (0, 1, 2, 3, 4, 5)) True is_subsequence([], ["a", "b", "c"]) True is_subsequence(["a"], []) False
Complexity: O(n) where n is len(main_sequence)
Source code in shortfx/fxPython/py_operations.py
list_has_list(container_list: list, search_list: list) -> bool
¶
Checks if all elements from one list exist in another list, regardless of order.
Problem/User Need: When comparing lists, it's often necessary to verify if all elements from one list exist in another list, without considering their order or position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
container_list
|
list
|
The larger list to search within. |
required |
search_list
|
list
|
The list whose elements we want to find. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if all elements in search_list exist in container_list, False otherwise. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If either argument is not a list. |
ValueError
|
If either list is empty. |
Example
list_has_list(['a', 'b', 'c', 'd'], ['b', 'c']) True list_has_list(['a', 'b', 'c'], ['b', 'd']) False list_has_list([1, 2, 3, 4], [2, 1]) True list_has_list([], [1, 2]) ValueError: Lists cannot be empty
Cost
Time complexity: O(n * m) where n and m are the lengths of the lists Space complexity: O(1) as we only use set operations
Source code in shortfx/fxPython/py_operations.py
list_intersection(p_list1: list, p_list2: list) -> set
¶
Finds the intersection of two lists, returning a set of common elements. It first filters out any falsy values (e.g., None, 0, '') from the input lists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p_list1
|
list
|
The first input list. |
required |
p_list2
|
list
|
The second input list. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
set |
set
|
A set containing elements that are present in both filtered lists. |
Example usage
list_a = [1, 2, None, 3, 4, 0, 5] list_b = [3, 4, 5, 6, '', 7] common_elements = list_intersection(list_a, list_b)
common_elements will be¶
Cost: O(n + m) on average, where n and m are the lengths of p_list1 and p_list2,¶
due to list comprehensions and set conversions/intersection.¶
Source code in shortfx/fxPython/py_operations.py
make_array(rows: int, columns: int, fn: Callable[[int, int], Any]) -> list[list[Any]]
¶
Generates a 2-D array using a function.
Description
Creates a rows×columns matrix where each cell value is computed by calling fn(row_index, col_index) with 0-based indices. Equivalent to Excel MAKEARRAY.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
int
|
Number of rows (>= 1). |
required |
columns
|
int
|
Number of columns (>= 1). |
required |
fn
|
Callable[[int, int], Any]
|
A callable that takes (row, col) and returns a value. |
required |
Returns:
| Type | Description |
|---|---|
list[list[Any]]
|
list[list[Any]]: The generated array. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If rows or columns < 1. |
TypeError
|
If fn is not callable. |
Example
make_array(2, 3, lambda r, c: (r + 1) * (c + 1)) [[1, 2, 3], [2, 4, 6]]
Complexity: O(rows × columns)
Source code in shortfx/fxPython/py_operations.py
merge_elements(first_collection: Iterable, second_collection: Iterable, return_type: str = 'list', remove_duplicates: bool = False) -> Union[list, tuple, set]
¶
Merges two collections into a single collection of the specified type.
This function is highly flexible, accepting lists, tuples, or sets as input for both collections. It combines all elements from both collections and returns them in the specified output type (list, tuple, or set).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
first_collection
|
Iterable
|
The first collection (list, tuple, or set) to merge. |
required |
second_collection
|
Iterable
|
The second collection (list, tuple, or set) to merge. |
required |
return_type
|
str
|
The desired type of the returned collection. Accepted values are "list", "tuple", or "set". Defaults to "list". |
'list'
|
remove_duplicates
|
bool
|
If True, removes duplicate elements from the merged result. Only applicable when return_type is "list" or "tuple". Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Union[list, tuple, set]
|
Union[list, tuple, set]: A new collection of the specified |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
Example of use
list_a = [1, 2, 3] list_b = [4, 5, 6] merge_elements(list_a, list_b, return_type="list") [1, 2, 3, 4, 5, 6]
tuple_a = ("a", "b", "c") set_b = {"c", "d", "e"} merge_elements(tuple_a, set_b, return_type="tuple") ('a', 'b', 'c', 'c', 'd', 'e')
list_a = [1, 2, 2, 3] list_b = [3, 4, 4, 5] merge_elements(list_a, list_b, return_type="list", remove_duplicates=True) [1, 2, 3, 4, 5]
set_a = {1, 2, 3} set_b = {3, 4, 5} merge_elements(set_a, set_b, return_type="set")
Cost
O(n + m) where n and m are the lengths of the input collections. If remove_duplicates is True and return_type is not "set", the cost becomes O(n + m) for creating a set and then converting back.
Source code in shortfx/fxPython/py_operations.py
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 | |
merge_json_strings(json_str_1: str, json_str_2: str) -> str
¶
Merges two JSON strings (representing JSON objects) into a new JSON string.
If both JSONs contain the same keys, the values from the second JSON (json_str_2) will overwrite the values from the first (json_str_1).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json_str_1
|
str
|
The first JSON string to merge (must represent a JSON object). |
required |
json_str_2
|
str
|
The second JSON string to merge (must represent a JSON object). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A new JSON string representing the merged object. |
Raises:
| Type | Description |
|---|---|
JSONDecodeError
|
If either input string is not a valid JSON. |
TypeError
|
If either input string does not represent a JSON object (dictionary). |
Example of use
merge_json_strings('{"name": "Alice", "age": 30}', '{"age": 31, "city": "New York"}') '{"name": "Alice", "age": 31, "city": "New York"}' merge_json_strings('{"a": 1}', '{"b": 2}') '{"a": 1, "b": 2}'
Cost: O(n + m), where n and m are the number of keys in the two dictionaries.
Source code in shortfx/fxPython/py_operations.py
partition(predicate: Callable, iterable: Iterable) -> Tuple[list, list]
¶
Splits an iterable into two lists based on a predicate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predicate
|
Callable
|
A callable returning True/False for each element. |
required |
iterable
|
Iterable
|
The collection to partition. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[list, list]
|
A tuple |
Example
partition(lambda x: x > 3, [1, 2, 3, 4, 5, 6]) ([4, 5, 6], [1, 2, 3]) partition(str.isupper, ["A", "b", "C", "d"]) (['A', 'C'], ['b', 'd'])
Cost: O(n) where n is the number of elements.
Source code in shortfx/fxPython/py_operations.py
pick_in_collection(collection: Iterable, prompt: str = 'Por favor, selecciona una opción:', allow_multiple: bool = False, return_index: bool = False, exit_on_cancel: bool = False) -> Union[Any, List[Any], int, List[int], None]
¶
Permite al usuario seleccionar una o varias opciones de cualquier colección iterable numerada.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
collection
|
Iterable
|
Una colección de elementos (lista, tupla, conjunto, etc.) de los que el usuario puede elegir. Los elementos pueden ser de cualquier tipo (cadenas, números, objetos, etc.). |
required |
prompt
|
(str, opcional)
|
El mensaje que se mostrará al usuario antes de la lista de opciones. Por defecto: "Por favor, selecciona una opción:". |
'Por favor, selecciona una opción:'
|
allow_multiple
|
(bool, opcional)
|
Si es True, el usuario puede seleccionar múltiples opciones separadas por comas (ej. "1,3,5"). Por defecto es False. |
False
|
return_index
|
(bool, opcional)
|
Si es True, la función devuelve el/los Ãndice/s (basado en 0) de la/s opción/es en la lista interna creada a partir de la colección. Si es False, devuelve el/los valor/es de la/s opción/es. Por defecto es False. |
False
|
exit_on_cancel
|
(bool, opcional)
|
Si es True, el programa terminará si el usuario introduce 'q' o 'cancelar'. Por defecto es False. |
False
|
Returns:
| Type | Description |
|---|---|
Union[Any, List[Any], int, List[int], None]
|
any | list[any] | int | list[int] | None: - El elemento seleccionado (si allow_multiple es False). - Una lista de elementos seleccionados (si allow_multiple es True). - El Ãndice del elemento seleccionado (si return_index es True y allow_multiple es False). - Una lista de Ãndices (si return_index es True y allow_multiple es True). - None si el usuario cancela (introduce 'q' o 'cancelar') y exit_on_cancel es False. |
Raises:
| Type | Description |
|---|---|
TypeError
|
Si la 'collection' proporcionada no es iterable. |
ValueError
|
Si la 'collection' está vacÃa. |
Ejemplos de uso
colores_tuple = ("Rojo", "Verde", "Azul", "Amarillo") color_elegido = pick_in_collection(colores_tuple, "Elige tu color favorito:") print(f"Has elegido: {color_elegido}")
numeros_set = {10, 20, 30, 40, 50} numeros_elegidos = pick_in_collection(numeros_set, "Elige algunos números:", allow_multiple=True) print(f"Has elegido: {numeros_elegidos}")
texto_generator = (f"Item {i}" for i in range(1, 6)) item_elegido = pick_in_collection(texto_generator, "Selecciona un Ãtem del generador:", return_index=True) print(f"El Ãndice del Ãtem elegido es: {item_elegido}")
Source code in shortfx/fxPython/py_operations.py
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 | |
pluck(iterable: Iterable, key: Any) -> list
¶
Extracts a single field from each element in a collection.
Works with dictionaries (by key) and objects (by attribute name).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
iterable
|
Iterable
|
A collection of dicts or objects. |
required |
key
|
Any
|
The dictionary key or attribute name to extract. |
required |
Returns:
| Type | Description |
|---|---|
list
|
A list of extracted values. |
Example
pluck([{"name": "Alice"}, {"name": "Bob"}], "name") ['Alice', 'Bob'] pluck([{"x": 1, "y": 2}, {"x": 3, "y": 4}], "x") [1, 3]
Cost: O(n) where n is the number of elements.
Source code in shortfx/fxPython/py_operations.py
search(collection: Iterable[Any], target_element: Any) -> Optional[Any]
¶
Searches for a target element within an iterable collection.
This function iterates through the provided collection to find the first
occurrence of the target_element. It is designed to work with any
iterable, such as lists, tuples, sets, and generators.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
collection
|
Iterable[Any]
|
The collection to be searched. |
required |
target_element
|
Any
|
The element to search for. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Any]
|
Optional[Any]: The found element, or |
Optional[Any]
|
The return type is |
Optional[Any]
|
might not return an element. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the provided |
Example of use
my_list = [1, 2, 3, 4, 5] search(my_list, 3) 3 search(my_list, 6) None
Cost
The time complexity is O(N) in the worst-case scenario, where N is the number of elements in the collection, as it may need to check every element. In the best case, it is O(1) if the element is the first in the collection. The space complexity is O(1) as no extra storage is needed.
Source code in shortfx/fxPython/py_operations.py
sequence(rows: int = 1, columns: int = 1, start: float = 1, step: float = 1) -> list[list[float]]
¶
Generates a 2-D array of sequential numbers.
Description
Returns a rows×columns matrix filled with values starting at start and incrementing by step. Equivalent to Excel SEQUENCE.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
int
|
Number of rows (>= 1). |
1
|
columns
|
int
|
Number of columns (>= 1). |
1
|
start
|
float
|
First value in the sequence. |
1
|
step
|
float
|
Increment between consecutive values. |
1
|
Returns:
| Type | Description |
|---|---|
list[list[float]]
|
list[list[float]]: A 2-D list of sequential values. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If rows or columns < 1. |
Example
sequence(2, 3) [[1, 2, 3], [4, 5, 6]] sequence(3, 1, 0, 5) [[0], [5], [10]]
Complexity: O(rows × columns)
Source code in shortfx/fxPython/py_operations.py
sort_by(data: List[Any], sort_keys: List[Any], reverse: bool = False) -> List[Any]
¶
Sorts data based on corresponding sort keys.
Description
Sorts the data list using the values in sort_keys to determine order. Both lists must be the same length. Equivalent to Excel SORTBY.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
List[Any]
|
The list of items to sort. |
required |
sort_keys
|
List[Any]
|
The list of values to sort by (same length as data). |
required |
reverse
|
bool
|
If True, sorts in descending order. |
False
|
Returns:
| Type | Description |
|---|---|
List[Any]
|
A new sorted list of data items. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If data and sort_keys have different lengths or are empty. |
Example
sort_by(["c", "a", "b"], [3, 1, 2]) ['a', 'b', 'c'] sort_by(["c", "a", "b"], [3, 1, 2], reverse=True) ['c', 'b', 'a']
Cost: O(n log n)
Source code in shortfx/fxPython/py_operations.py
sort_dict_by_key(d: dict, reverse: bool = False) -> dict
¶
Return a new dict sorted by keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict
|
Input dictionary. |
required |
reverse
|
bool
|
If True, sort descending. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
dict
|
Ordered dict sorted by keys. |
Example
sort_dict_by_key({'c': 3, 'a': 1, 'b': 2})
Complexity: O(n log n)
Source code in shortfx/fxPython/py_operations.py
sort_dict_by_value(d: dict, reverse: bool = False) -> dict
¶
Return a new dict sorted by values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict
|
Input dictionary. |
required |
reverse
|
bool
|
If True, sort descending. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
dict
|
Ordered dict sorted by values. |
Example
sort_dict_by_value({'b': 2, 'a': 1, 'c': 3})
Complexity: O(n log n)
Source code in shortfx/fxPython/py_operations.py
sort_dicts_by_key(items: list[dict], key: str, reverse: bool = False) -> list[dict]
¶
Sorts a list of dictionaries by a specific key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[dict]
|
The list of dictionaries to sort. |
required |
key
|
str
|
The dictionary key to sort by. |
required |
reverse
|
bool
|
If True, sorts in descending order. |
False
|
Returns:
| Type | Description |
|---|---|
list[dict]
|
A new sorted list of dictionaries. |
Example
sort_dicts_by_key([{"n": 3}, {"n": 1}, {"n": 2}], "n") [{'n': 1}, {'n': 2}, {'n': 3}]
Cost: O(n log n)
Source code in shortfx/fxPython/py_operations.py
take_from_array(array: list[list[Any]], rows: int | None = None, columns: int | None = None) -> list[list[Any]]
¶
Takes the first or last rows/columns from a 2-D array.
Description
If rows > 0, takes from the top; if rows < 0, takes from the bottom. Same logic for columns (left/right). Equivalent to Excel TAKE.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
list[list[Any]]
|
A 2-D list. |
required |
rows
|
int | None
|
Number of rows to take (positive=top, negative=bottom). |
None
|
columns
|
int | None
|
Number of columns to take (positive=left, negative=right). |
None
|
Returns:
| Type | Description |
|---|---|
list[list[Any]]
|
list[list[Any]]: The extracted sub-array. |
Example
take_from_array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], rows=2, columns=-2) [[2, 3], [5, 6]] take_from_array([[1, 2], [3, 4], [5, 6]], rows=-1) [[5, 6]]
Complexity: O(rows × cols)
Source code in shortfx/fxPython/py_operations.py
tocol(array: list, scan_by_column: bool = False) -> list
¶
Flatten a 2-D array into a single-column list of lists.
Description
Converts a 2-D array to column format [[v1],[v2],...]. Equivalent to Excel TOCOL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
list
|
2-D list. |
required |
scan_by_column
|
bool
|
If True, scan column-first; otherwise row-first. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
list
|
List of single-element lists. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If array is not a list. |
Example
tocol([[1, 2], [3, 4]]) [[1], [2], [3], [4]] tocol([[1, 2], [3, 4]], scan_by_column=True) [[1], [3], [2], [4]]
Complexity: O(r × c)
Source code in shortfx/fxPython/py_operations.py
torow(array: list, scan_by_column: bool = False) -> list
¶
Flatten a 2-D array into a single-row list.
Description
Converts a 2-D array to row format [[v1, v2, ...]]. Equivalent to Excel TOROW.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
list
|
2-D list. |
required |
scan_by_column
|
bool
|
If True, scan column-first; otherwise row-first. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
list
|
A list containing one list with all values. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If array is not a list. |
Example
torow([[1, 2], [3, 4]]) [[1, 2, 3, 4]] torow([[1, 2], [3, 4]], scan_by_column=True) [[1, 3, 2, 4]]
Complexity: O(r × c)
Source code in shortfx/fxPython/py_operations.py
unflatten_dict(d: dict, separator: str = '.') -> dict
¶
Reconstructs a nested dictionary from a flat one.
Composite keys are split by separator to create nested levels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict
|
The flat dictionary with composite keys. |
required |
separator
|
str
|
The separator used in the keys (default "."). |
'.'
|
Returns:
| Type | Description |
|---|---|
dict
|
A nested dictionary. |
Example
unflatten_dict({"a.b": 1, "a.c.d": 2}) {'a': {'b': 1, 'c': {'d': 2}}}
Cost: O(n*k) where k is average key depth.
Source code in shortfx/fxPython/py_operations.py
unique_list(p_list: List[Any]) -> List[Any]
¶
Returns a new list containing only the unique elements from the original list.
The order of elements in the resulting list is not guaranteed, as a set is used internally for deduplication.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p_list
|
List[Any]
|
The input list which may contain duplicate elements. |
required |
Returns:
| Type | Description |
|---|---|
List[Any]
|
List[Any]: A new list containing all unique elements from the input list. |
Example of use
unique_list([1, 2, 2, 3, 1]) [1, 2, 3] # Order may vary unique_list(["apple", "banana", "apple"]) ['banana', 'apple'] # Order may vary
Cost: O(n), where n is the number of elements in the list.
Source code in shortfx/fxPython/py_operations.py
unique_tuple_list(p_list: list[tuple]) -> list[tuple]
¶
Removes duplicate tuples from a list based on the first element of each tuple. Returns a new list containing only the unique tuples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p_list
|
list[tuple]
|
The input list of tuples. Each tuple must have at least one element. |
required |
Returns:
| Type | Description |
|---|---|
list[tuple]
|
list[tuple]: A new list containing the unique tuples, maintaining the order of their first appearance in the original list. |
Example usage
my_tuples = [(1, 'apple'), (2, 'banana'), (1, 'orange'), (3, 'grape'), (2, 'kiwi')] unique_list = unique_tuple_list(my_tuples)
unique_list will be [(1, 'apple'), (2, 'banana'), (3, 'grape')]¶
Cost: O(n) on average, where n is the number of tuples in p_list,¶
due to set lookups and list appends.¶
Source code in shortfx/fxPython/py_operations.py
vlookup(lookup_value: Any, table: List[List[Any]], col_index: int, approximate: bool = False) -> Any
¶
Searches for a value in the first column and returns a value from another column.
Description
Looks up a value in the first column of a table (list of rows) and returns the corresponding value from the specified column index. Equivalent to Excel VLOOKUP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lookup_value
|
Any
|
The value to search for in the first column. |
required |
table
|
List[List[Any]]
|
A list of rows (lists), each with the same number of columns. |
required |
col_index
|
int
|
The 1-based column index to return (1 = first column). |
required |
approximate
|
bool
|
If True, finds the closest match less than or equal to the lookup value (table must be sorted ascending by first column). If False, requires an exact match. |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
The value from the matching row at the specified column. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no match is found, col_index is out of range, or table is empty. |
TypeError
|
If table is not a list of lists. |
Example
table = [[1, "a"], [2, "b"], [3, "c"]] vlookup(2, table, 2) 'b' vlookup(2.5, [[1, "x"], [2, "y"], [3, "z"]], 2, approximate=True) 'y'
Cost: O(n) for exact match, O(n) for approximate match.
Source code in shortfx/fxPython/py_operations.py
1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 | |
vstack(*arrays: list[list[Any]]) -> list[list[Any]]
¶
Vertically stacks 2-D arrays on top of each other.
Description
Joins multiple 2-D arrays by appending rows. All arrays must have the same number of columns. Equivalent to Excel VSTACK.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*arrays
|
list[list[Any]]
|
Two or more 2-D arrays. |
()
|
Returns:
| Type | Description |
|---|---|
list[list[Any]]
|
list[list[Any]]: Combined array. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If arrays have different column counts. |
Example
vstack([[1, 2]], [[3, 4], [5, 6]]) [[1, 2], [3, 4], [5, 6]]
Complexity: O(total_rows × cols)
Source code in shortfx/fxPython/py_operations.py
wrap_rows(vector: list[Any], wrap_count: int, pad_with: Any = None) -> list[list[Any]]
¶
Wraps a 1-D vector into a 2-D array by rows.
Description
Splits a flat list into rows of wrap_count elements. The last row is padded with pad_with if needed. Equivalent to Excel WRAPROWS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector
|
list[Any]
|
Flat list of values. |
required |
wrap_count
|
int
|
Number of elements per row (>= 1). |
required |
pad_with
|
Any
|
Value used to pad the last incomplete row. |
None
|
Returns:
| Type | Description |
|---|---|
list[list[Any]]
|
list[list[Any]]: A 2-D array. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If wrap_count < 1. |
Example
wrap_rows([1, 2, 3, 4, 5], 2) [[1, 2], [3, 4], [5, None]] wrap_rows([1, 2, 3, 4], 2) [[1, 2], [3, 4]]
Complexity: O(n)
Source code in shortfx/fxPython/py_operations.py
xlookup(lookup_value: Any, lookup_array: List[Any], return_array: List[Any], if_not_found: Any = None, match_mode: int = 0) -> Any
¶
Searches a lookup array and returns the corresponding value from a return array.
Description
A more flexible lookup than vlookup/hlookup. Searches lookup_array for lookup_value and returns the corresponding element from return_array. Equivalent to Excel XLOOKUP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lookup_value
|
Any
|
The value to search for. |
required |
lookup_array
|
List[Any]
|
The array to search in. |
required |
return_array
|
List[Any]
|
The array to return a value from (same length). |
required |
if_not_found
|
Any
|
Value to return if no match is found (default None). |
None
|
match_mode
|
int
|
0 = exact match, -1 = exact or next smaller, 1 = exact or next larger. |
0
|
Returns:
| Type | Description |
|---|---|
Any
|
The matching value from return_array, or if_not_found. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If lookup_array and return_array have different lengths. |
Example
xlookup("b", ["a", "b", "c"], [1, 2, 3]) 2 xlookup("z", ["a", "b", "c"], [1, 2, 3], "Not Found") 'Not Found' xlookup(25, [10, 20, 30], ["x", "y", "z"], match_mode=-1) 'y'
Cost: O(n)
Source code in shortfx/fxPython/py_operations.py
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 | |
xmatch(lookup_value: Any, lookup_array: list[Any], match_mode: int = 0, search_mode: int = 1) -> int
¶
Returns the 1-based position of a value in an array.
Description
Searches lookup_array for lookup_value and returns its relative position (1-based). Supports exact, next smaller, next larger, and wildcard matching. Equivalent to Excel XMATCH.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lookup_value
|
Any
|
The value to search for. |
required |
lookup_array
|
list[Any]
|
The array to search. |
required |
match_mode
|
int
|
0=exact, -1=exact or next smaller, 1=exact or next larger, 2=wildcard (* and ?). |
0
|
search_mode
|
int
|
1=first-to-last, -1=last-to-first. |
1
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
1-based position of the match. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no match is found. |
Example
xmatch(30, [10, 20, 30, 40]) 3 xmatch(25, [10, 20, 30, 40], match_mode=-1) 2
Complexity: O(n)
Source code in shortfx/fxPython/py_operations.py
2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 | |
zip_dict(keys: List[Any], values: List[Any]) -> dict
¶
Create a dictionary from two parallel lists of keys and values.
If lists differ in length, extra elements are dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
List[Any]
|
List of keys. |
required |
values
|
List[Any]
|
List of values. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary mapping keys[i] to values[i]. |
Example
zip_dict(['a', 'b', 'c'], [1, 2, 3])
Complexity: O(n)