How to remove one of the duplicate values that are next to each other in a list?

半世苍凉 提交于 2021-02-10 09:24:54

问题


x1 = [5, 5]
x2 = [1, 5, 5, 2]
x3 = [5, 5, 1, 2, 5, 5]
x4 = [5, 5, 1, 5, 5, 2, 5, 5]
x5 = [5, -5]
x6 = [1, 2, 3, 4]
x7 = [5, 5, 5, 5, 5, 5]

How do I remove one of the duplicate values that are next to each other on every list?

After all one of the duplicate values that are next to each other are removed, they should look like this:

x1 = [5]
x2 = [1, 5, 2]
x3 = [5, 1, 2, 5]
x4 = [5, 1, 5, 2, 5]
x5 = [5, -5]
x6 = [1, 2, 3, 4]
x7 = [5]

回答1:


When there can be three or more values in a row and only a single value is wanted:

from itertools import groupby

def remove_consecutive_duplicates(iterable):
    return [v for v, g in groupby(iterable)]



回答2:


Simple list comprehension would do:

>>> x = [5, 5, 1, 5, 2, 5, 5]
>>> [a for a, b in zip(x, x[1:]) if a != b] + [x[-1]]
[5, 1, 5, 2, 5]

You are basically taking each element if the next one differs, plus the last element.




回答3:


You can just loop over your list while keeping track of the previous value, and only keep the next value if they differ:

def uniquefy_conseq_vals(my_list):
    prev = None
    new_list = []
    for ele in my_list:
        if ele != prev:
            new_list.append(ele)
        prev = ele
    return new_list

if __name__ == "__main__":

    x1 = [5, 5]
    x2 = [1, 5, 5, 2]
    x3 = [5, 5, 1, 2, 5, 5]
    x4 = [5, 5, 1, 5, 5, 2, 5, 5]
    x5 = [5, -5]
    x6 = [1, 2, 3, 4]
    x7 = [5, 5, 5, 5, 5, 5]

    print uniquefy_conseq_vals(x1)
    print uniquefy_conseq_vals(x2)
    print uniquefy_conseq_vals(x3)
    print uniquefy_conseq_vals(x4)
    print uniquefy_conseq_vals(x5)
    print uniquefy_conseq_vals(x6)
    print uniquefy_conseq_vals(x7)


来源:https://stackoverflow.com/questions/44393491/how-to-remove-one-of-the-duplicate-values-that-are-next-to-each-other-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!