字符串去重

例如‘aabbcc’,去重后为‘abc’

同样是两种方法,一种是循环迭代

def shrink_consecutive_nb(list_of_nb):
    output = f'{list_of_nb[0]}'
    for i in range(1, len(list_of_nb)):
        if list_of_nb[i] != list_of_nb[i - 1]:
            output += list_of_nb[i]
    return output

另一种是递归

def remove_repeated_value(string):
    if not string:
        return ''
    if len(string) == 1:
        return string
    L = remove_repeated_value(string[1:])
    if string[0] in L:
        return L
    else:
        return string[0] + L

猜你喜欢

转载自www.cnblogs.com/AcodingDg/p/9094132.html