[Tutor] Duplicate items in list

Mats Wichmann mats at wichmann.us
Fri Oct 9 12:56:02 EDT 2020


On 10/9/20 10:41 AM, Manprit Singh wrote:
> Dear Mats Wichmann,
> 
> Here in this question my purpose is not to remove duplicates from the
> list.This question is about removing duplicates from the groups.
> see  the list is lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5], the
> output i need is :
> 3
> 5
> 6
> 5
> 9
> 3
> 5
> As you can see 3 and 5 are still repeating in the output ,  there are 2
> groups of 3 in the list, i have to write a program that gives a single
> three for each group of 3, in that way 3 will occur in the output  for 2
> times, for the same reason 5 will occur in the output for 3 times .

Once you used the word group it triggered the memory that There's a
Method For That: itertools.groupby.

>>> lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5]
>>> z = itertools.groupby(lst)
>>> # groupby gives you back the list split into tuples representing the
groups
>>> print(*z)
(3, <itertools._grouper object at 0x7f2fe1089fd0>) (5,
<itertools._grouper object at 0x7f2fe0fff050>) (6, <itertools._grouper
object at 0x7f2fe0fff090>) (5, <itertools._grouper object at
0x7f2fe0fff0d0>) (9, <itertools._grouper object at 0x7f2fe0fff110>) (3,
<itertools._grouper object at 0x7f2fe0fff150>) (5, <itertools._grouper
object at 0x7f2fe0fff190>)
>>> # So a possible solution:
>>> nodupes = [x[0] for x in itertools.groupby(lst)]
>>> nodupes
[3, 5, 6, 5, 9, 3, 5]



More information about the Tutor mailing list