def sort_metrics(metric_names):
    """
    Sort a list of metrics, so that errors are right after their variable.
    The format of the metric names have to be e.g. e_loss and e_err_loss
    for this to work.

    Example
    ----------
    >>> sort_metrics( ['e_loss', 'loss', 'e_err_loss', 'dx_err_loss'] )
    ['e_loss', 'e_err_loss', 'loss', 'dx_err_loss']

    Parameters
    ----------
    metric_names : List
        List of metric names.

    Returns
    -------
    sorted_metrics : List
        List of sorted metric names with the same length as the input.

    """
    sorted_metrics = [0] * len(metric_names)
    counter = 0
    for metric_name in metric_names:
        if 'err_' in metric_name:
            if metric_name.replace('err_', '') not in metric_names:
                sorted_metrics[counter] = metric_name
                counter += 1
            continue
        sorted_metrics[counter] = metric_name
        counter += 1
        err_loss = metric_name.split('_loss')[0] + '_err_loss'
        if err_loss in metric_names:
            sorted_metrics[counter] = err_loss
            counter += 1
    assert 0 not in sorted_metrics, 'Something went wrong with the sorting of metrics! Given was {}, output was {}. '.format(
        metric_names, sorted_metrics)
    return sorted_metrics
