[Tutor] Looking for duplicates within a list [SOLVED]
Ken G.
beachkid at insightbb.com
Fri Jun 11 17:16:38 CEST 2010
Sander Sweers wrote:
> On 11 June 2010 15:57, Ken G. <beachkid at insightbb.com> wrote:
>
>> In any event, if a number is listed more than once, I would like to know how
>> many times, such as 2 or 3 times. For example, '3' is listed twice within a
>> list.
>>
>
> If you do not have top keep the order of the number this will work.
>
>
>>>> a = [1, 2, 3, 3, 4]
>>>> counted = {}
>>>> for n in a:
>>>>
> if not n in counted:
> counted[n] = 1
> else:
> counted[n] += 1
>
>
>>>> counted
>>>>
> {1: 1, 2: 1, 3: 2, 4: 1}
>
>
>>>> for x, y in counted.items():
>>>>
> if y > 1:
> print "Number %s was found %s times" % (x, y)
> else:
> print "Number %s was found %s time" % (x, y)
>
> Number 1 was found 1 time
> Number 2 was found 1 time
> Number 3 was found 2 times
> Number 4 was found 1 time
>
> Greets
> Sander
>
That works great! Thanks!
Ken
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100611/a4ad0f58/attachment.html>
More information about the Tutor
mailing list