I have an issue with removing consecutive duplicates in a list without removing all duplicates.
Say I have a list,
a = [3,3,3,4,10,11,3,3,5,5,10]
What I want to do is whenever there is a duplicate in a row, that duplicate is changed to a single value. I want this to happen for any number of consecutive duplicates. Thus I want my new a to be,
new_a = [3,4,10,11,3,5,10]
Notice I don't want to remove the other duplicates, like the set function would do, I just want to change consecutive duplicates into one value.
Here is my attempt, which works sometimes but not on all my lists, most likely because I'm not sure how to set up the general rule for my range.
for i in range(0, len(set(a))-1):
if a[i] == a[i 1]:
a.pop(i 1)
Any help would be great, thanks.
CodePudding user response:
This might help
a=[3,3,4,10,11,3,5,5,0,0,10,11,11,10,10,0,0]
i=0
while(i<(len(a)-1)):
if a[i]==a[i 1]:
a.pop(i 1)
i =1
print(a)
CodePudding user response:
a = [3,3,3,4,10,11,3,3,5,5,10]
new_a = []
for i in range(len(a)):
if a[i] != a[i-1]:
new_a.append(a[i])
print(new_a)
[3, 4, 10, 11, 3, 5, 10]
CodePudding user response:
You can keep track of last item while iterating the list and append the current item to result only if the it is different from the last seen item.
In terms of code,
def solve(l):
seen = l[0]
ans = [l[0]]
for i in l[1:]:
if i != seen:
ans = [i]
seen = i
return ans
solve([1, 1, 1, 2, 1])
[1, 2, 1]
solve([3,3,3,4,10,11,3,3,5,5,10])
[3, 4, 10, 11, 3, 5, 10]
CodePudding user response:
You could do it like this:
a = [3,3,3,4,10,11,3,3,5,5,10]
b = [a[0]]
for x in a[1:]:
if x != b[-1]:
b.append(x)
print(b)
Of course, this creates a new list so you could just replace a with b
CodePudding user response:
Does this help you?
mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
CodePudding user response:
You can use numpy.ediff1d
method:
np.array(a)[np.concatenate(([1],np.ediff1d(a)))!=0].tolist()
Output:
[ 3, 4, 10, 11, 3, 5, 10]