mmengine.utils.apply_to¶
- mmengine.utils.apply_to(data, expr, apply_func)[source]¶
Apply function to each element in dict, list or tuple that matches with the expression.
For examples, if you want to convert each element in a list of dict from np.ndarray to Tensor. You can use the following code:
Examples
>>> from mmengine.utils import apply_to >>> import numpy as np >>> import torch >>> data = dict(array=[np.array(1)]) # {'array': [array(1)]} >>> result = apply_to(data, lambda x: isinstance(x, np.ndarray), lambda x: torch.from_numpy(x)) >>> print(result) # {'array': [tensor(1)]}
- Parameters:
data (Any) – Data to be applied.
expr (Callable) – Expression to tell which data should be applied with the function. It should return a boolean.
apply_func (Callable) – Function applied to data.
- Returns:
The data after applying.
- Return type:
Any