Home > Backend Development > Python Tutorial > How Can I Efficiently Remove Consecutive Duplicate Elements in Python?

How Can I Efficiently Remove Consecutive Duplicate Elements in Python?

DDD
Release: 2024-12-05 17:37:11
Original
452 people have browsed it

How Can I Efficiently Remove Consecutive Duplicate Elements in Python?

Eliminating Consecutive Duplicate Elements in Python

In Python, the task of eliminating consecutive duplicate elements from a list can be approached in multiple ways. One approach involves iterating through the list and deleting adjacent elements with the same value. However, this method can become cumbersome when dealing with long lists.

For more efficient and elegant solutions, we can leverage Python's built-in functions and libraries. Using itertools.groupby, we can group consecutive duplicate elements and manipulate the resulting generator accordingly.

To eliminate all consecutive duplicate elements, we simply need to extract the keys from the grouped iterator.

L = [1,1,1,1,1,1,2,3,4,4,5,1,2]
from itertools import groupby
[key for key, _group in groupby(L)]
Copy after login

Output:

[1, 2, 3, 4, 5, 1, 2]
Copy after login

For the second part of the question, which requires eliminating only the elements that have consecutive duplicates, we can further filter the grouped iterator based on the number of elements in each group. Using a generator expression, we can sum the elements to determine if there's more than one element in the group.

[k for k, g in groupby(L) if sum(1 for i in g) < 2]
Copy after login

Output:

[2, 3, 5, 1, 2]
Copy after login

This technique is more Pythonic and efficient compared to the initial attempt. It leverages Python's built-in functions to group and filter the list, resulting in a concise and readable solution.

The above is the detailed content of How Can I Efficiently Remove Consecutive Duplicate Elements in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template