首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

优雅的方法来删除列表中连续的重复元素?

优雅的方法来删除列表中连续的重复元素:

方法一:使用Python的内置函数

代码语言:python
复制
def remove_consecutive_duplicates(lst):
    return [x for i, x in enumerate(lst) if i == 0 or x != lst[i-1]]

方法二:使用itertools库

代码语言:python
复制
import itertools

def remove_consecutive_duplicates(lst):
    return list(itertools.groupby(lst))

方法三:使用zip函数

代码语言:python
复制
def remove_consecutive_duplicates(lst):
    return [x for x, _ in zip(lst, range(len(lst)))]

方法四:使用双指针

代码语言:python
复制
def remove_consecutive_duplicates(lst):
    if not lst:
        return []
    slow, fast = 0, 1
    while fast < len(lst):
        if lst[fast] != lst[slow]:
            slow += 1
            lst[slow] = lst[fast]
        fast += 1
    return lst[:slow+1]

以上方法均可以有效地删除列表中连续的重复元素,具体选择哪种方法取决于个人喜好和代码可读性需求。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券