[Tutor] Looking for duplicates within a list
Jose Amoreira
ljmamoreira at gmail.com
Fri Jun 11 16:49:22 CEST 2010
On Friday, June 11, 2010 02:57:34 pm Ken G. wrote:
> I have been working on this problem for several days and I am not making
> any progress. I have a group of 18 number, in ascending order, within a
> list. They ranged from 1 to 39. Some numbers are duplicated as much as
> three times or as few as none.
>
> I started with one list containing the numbers. For example, they are
> listed as like below:
>
> a = [1, 2, 3, 3, 4]
>
> I started off with using a loop:
>
> for j in range (0, 5):
> x = a[0] # for example, 1
>
> How would I compare '1' with 2, 3, 3, 4?
>
> Do I need another duplicated list such as b = a and compare a[0] with
> either b[0], b[1], b[2], b[3], b[4]?
>
> Or do I compare a[0] with a[1], a[2], a[3], a[4]?
>
> 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.
>
> TIA,
>
I would do it with a dictionary:
def reps(lst):
dict = {}
for item in lst:
if item in dict:
dict[item] += 1
else:
dict[item] = 1
return dict
This function returns a dictionary with of the number of times each value in
the list is repeated. Even shorter using dict.setdefault:
def reps(lst):
dict={}
for item in lst:
dict[item] = dict.setdefault(item,0) + 1
return dict
For instance, if lst=[1,2,2,2,4,4,5], then reps(lst) returns
{1: 1, 2: 3, 4: 2, 5: 1}
Using the fact that the list is ordered, one can design a more efficient
solution (go through the list; if this item is equal to the previous, then it
is repeated, else, it is a new value). But you list is short enough for this
direct approach to work.
Hope this helps. Cheers,
Jose
More information about the Tutor
mailing list