python 如何将不完全连续的整数序列按[1-5,6,8-10]的格式输出,给出函数代码

def format_integer_sequence(seq):
    formatted_seq = []
    start = None
    end = None

    for num in sorted(seq):
        if start is None:
            start = num
            end = num
        elif num == end + 1:
            end = num
        else:
            if start == end:
                formatted_seq.append(str(start))
            else:
                formatted_seq.append(f"{start}-{end}")
            start = num
            end = num

    if start is not None:
        if start == end:
            formatted_seq.append(str(start))
        else:
            formatted_seq.append(f"{start}-{end}")

    formatted_output = ",".join(formatted_seq)
    return formatted_output

# 测试函数
sequence = [1, 2, 3, 5, 6, 8, 9, 10]
formatted_result = format_integer_sequence(sequence)
print(formatted_result)
def format_list(lst):
    res = []
    i = 0
    while i < len(lst):
        if i == len(lst) - 1 or lst[i + 1] != lst[i] + 1:
            res.append(str(lst[i]))
        else:
            j = i
            while j < len(lst) - 1 and lst[j + 1] == lst[j] + 1:
                j += 1
            res.append(str(lst[i]) + '-' + str(lst[j]))
            i = j
        i += 1
    return ','.join(res)

lst = [1,2,3,5,6,8,9,10]
print(format_list(lst))
Instance.df.机台.reset_index().pivot_table(
    index=['机台'], 
    values=['index'], 
    aggfunc=format_integer_sequence
)