Brian van den Broek wrote: [...]
Hi Srini,
for the task of finding out which items are repeated and how many times, I'd do this:
<code> def dups_in_list_report(a_list): '''Prints a duplication report for a list.'''
items_dict = {}
for i in a_list: if i in items_dict: items_dict[i] = items_dict[i] + 1 else: items_dict[i] = 1
get(key, default) is your friend here: for i in a_list: items_dict[i] = items_dict.get(i, 0) + 1
get() (and his "brother" setdefault()) are mighty dictionary-methods.
>for key in items_dict.copy(): # Try it without the .copy() if items_dict[key] == 1: # and see what happens. del items_dict[key]
dict_keys = items_dict.keys() dict_keys.sort()
This whole part can be rewritten (without sorting, but in Py2.4 you can use sorted() for this) with a list comprehension (Old Python2.1 style, with a newer version the keys() aren't needed):for key in dict_keys: print '%s occurred %s times' %(key, items_dict[key])
for k,v in [(k, items_dict[k]) \
for k in items_dict.keys() if items_dict[k] > 1]:
print '%s occurred %s times' %(key, items_dict[key])
f = [1,1,2,3,3,3,3,4,4,4,4,4,4,4,5]
dups_in_list_report(f) </code>
And, now that I get back on-line, I see that Chad posted the same basic idea. But, perhaps the extra stuff here is of use, too.
You can apply the get() there, too ;-)
HTH,
Brian vdB
HTH, Wolfram
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor