如果它与前一个元素相同,则删除列表中的元素

时间:2016-10-02 23:28:49

标签: list python-3.x

我现在已经坚持了一段时间。这听起来很简单但是到目前为止我一直在使用的代码。基本上这个函数在列表中传递了一堆数字,例如a_list = [1,2,3,3,4,3],我应该得到[1,2,3,4,3]

"AWS4-HMAC-SHA256
20161002T231640Z
20161002/ap-northeast-1/execute-api/aws4_request
fb4f7ebdcb405bceed598ecc097267b929eeb3f8f075b1b7a776f53c8c8c6168"

5 个答案:

答案 0 :(得分:4)

std::map可以轻松完成这项工作:

itertools.groupby

或者更简单的一个班轮:

In [28]: L = [1,2,3,3,4,3]

In [29]: answer = [k for k,_g in itertools.groupby(L)]

In [30]: answer
Out[30]: [1, 2, 3, 4, 3]

答案 1 :(得分:1)

您可以使用generator:

def remove_doubles(a_list):
    duplicate = None
    for item in a_list:
        if duplicate != item:
            duplicate = item 
            yield item

a_list = [1, 2, 3, 3, 4, 3]
print(list(remove_doubles(a_list))) # [1, 2, 3, 4, 3]

检查最后一项是否与当前项目相同,如果不是,则返回该项目。否则转到列表中的下一个项目,进程从头开始。如您所见,我将duplicate的初始值用作None,因此我们可以在第一次迭代期间进行第一次比较。

答案 2 :(得分:0)

>>> a_list = [1, 2, 3, 3, 4, 3]
>>> 
>>> def remove_doubles(a_list):
...     prev_item = a_list[0]
...     # the first item in our "to_return" list will be the first item in the input array
...     to_return = [prev_item]
...     i = 1
...     while i < len(a_list):
...         # if the current element equals the previous element, do nothing (i.e. don't append the current element)
...         if a_list[i] == prev_item:
...             pass
...         else:
...             # otherwise, reassign the current element to prev_item
...             # since we know it's unique, we can append it to our list to be returned
...             prev_item = a_list[i]
...             to_return.append(prev_item)
...         i += 1
...     return to_return
...             
... 
>>> remove_doubles(a_list)
[1, 2, 3, 4, 3]

答案 3 :(得分:0)

也许这就是你要找的东西:

def remove_doubles(a_list):
    new_list = a_list[:1]
    for i in range(1, len(a_list)):
        if new_list[-1] != a_list[i]:
            new_list.append(a_list[i])
    return new_list

编辑:

如果您想要变异a_list以删除相邻的重复值,而不是简单地删除删除它们的新列表,则只需将return new_list更改为a_list[:] = new_list

答案 4 :(得分:-1)

这应该有用。

def remove_doubles(a_list):
    new_list = [a_list[0]]
    for i in range(1, len(a_list)):
        if a_list[i] != a_list[i-1]:
            new_list.append(a_list[i])
    return new_list