I want to delete the consecutive duplicate values from the array and count unique consecutive values. But I am not getting expected result. Please check and help. Current Output: [aa, bb, aa, cc, cc, dd, ee, cc] [1, 1, 1, 2, 2, 2, 1, 1] Expected Output: [aa, bb, aa, cc, dd, ee, cc] [1, 1, 1, 4, 2, 1, 1] https://code.sololearn.com/W69Q4IqextAQ/?ref=app Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: . Show
You can also select a web site from the following list: How to Get Best Site PerformanceSelect the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location. Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: . You can also select a web site from the following list: How to Get Best Site PerformanceSelect the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location. In this article, we will discuss 3 different ways of removing consecutive duplicate elements from a python list. This is what we want to achieve.
So we are not removing all duplicated elements. We are only eliminating consecutive duplicate elements. Let’s check out the 3 different ways. Method 1 - For loops will never go out of fashion
Method 2 - Let’s be more Pythonic! Use Enumerate Here is a one-liner solution to the problem.
Tell me that wasn’t pretty !! Method 3 - It’s Python! There must be a library Here is the 3rd way using the
Now the question is, which one of the above methods is the fastest? Using the You can see that the 3rd approach (using the itertools library) is the fastest of all the 3 ways discussed in this article. Hope you enjoyed this article. Let me know if you have a better way of doing this, through the comments. When it is required to get the count of consecutive identical elements in a list, an iteration, the ‘append’ method, and the ‘set’ method are used. ExampleBelow is a demonstration of the same my_list = [24, 24, 24, 15, 15, 64, 64, 71, 13, 95, 100] print("The list is :") print(my_list) my_result = [] for index in range(0, len(my_list) - 1): if my_list[index] == my_list[index + 1]: my_result.append(my_list[index]) my_result = len(list(set(my_result))) print("The result is :") print(my_result) OutputThe list is : [24, 24, 24, 15, 15, 64, 64, 71, 13, 95, 100] The result is : 3 Explanation
|