Re: [Tutor] Detecting different list elements and counting them
by Alan Gauld other posts by this author
Dec 11 2003 7:39PM messages near this date
[Tutor] Detecting different list elements and counting them
|
Re: [Tutor] Detecting different list elements and counting them
> my_list = [ 'ABC', 'E', 'ABC', 'ABC', 'HJ', 'HJ' ]
>
> It would be nice to have the information which elements are in
the list
> and how many times these elements appear in the list.
>
> A dictionary as the result like the following would be fine.
>
> my_dict = {'ABC':3, 'E':1, 'HJ':2}
You just answered your own question, coz that's exactly what to
do.
my_dict = {}
for item in my_list:
if item in my_dict:
my_dict[item] += 1
else: my_dict[item] = 1
There might be a slightly cleverer way to do it using
my_dict(get)
but I can't be bothered thinking about it... :-)
Alan g.
_______________________________________________
Tutor maillist - Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor
Thread:
Michael Grabietz
Alan Gauld
Terry Carroll
Zak Arntson
Edward Comber
|