ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> python-Tutor
python-Tutor
RE: [Tutor] Detecting different list elements and counting them
by Edward Comber other posts by this author
Dec 11 2003 4:21PM messages near this date
RE: [Tutor] Detecting different list elements and counting them | [Tutor] Detecting different list elements and counting them
Bugger. This works..

my_list = [ 'ABC', 'E', 'ABC', 'ABC', 'HJ', 'HJ' ]

my_dict = {}
for item in my_list:
	if my_dict.has_key(item):
		my_dict[item] = my_dict[item] + 1
	else:
		my_dict[item] = 1

print my_dict

-----Original Message-----
From: Edward Comber [mailto:comber@[...].uk]
Sent: 11 December 2003 16:00
To: Michael Grabietz; tutor@[...].org
Subject: RE: [Tutor] Detecting different list elements and counting them


I would imagine something like

my_dict = {}
for item in my_list:
	if my_dict.haskey(item):
		my_dict[item] = my_dict[item] + 1
	else:
		my_dict[item] = 0


-----Original Message-----
From: tutor-bounces@[...].org [mailto:tutor-bounces@[...].org]On
Behalf Of Michael Grabietz
Sent: 11 December 2003 15:14
To: tutor@[...].org
Subject: [Tutor] Detecting different list elements and counting them


Hi,

I have a list like the following:

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}


Thank you for any ideas or hints.

Michael





_______________________________________________
Tutor maillist  -  Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor


_______________________________________________
Tutor maillist  -  Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved