[Tutor] Functional question

Kent Johnson kent37 at tds.net
Fri Aug 5 22:32:08 CEST 2005


Bernard Lebel wrote:
> Hello,
> 
> This question is not strictly bound to Python, but rather some
> functional programming problem, I hope someone can help me or suggest
> ressources.
> 
> 1 --
> I have a list of lists. Each of these lists has 3 elements: a string,
> and two integers. Thoughout the lists, there are only two different
> integers for the first one, and two different for the second one.
> 
> aLists = [
> 	[ 'Pass1', 10, 200 ],
> 	[ 'Pass2', 10, 200 ],
> 	[ 'Pass3', 25, 100 ],
> 	[ 'Pass4', 10, 100 ],
> 	[ 'Pass5', 25, 200 ] ]
> 
> 
> 
> 2 --
> Then I want to regroup the strings into two dictionaries. The first
> dictionaries is for the strings that have the same first integer, and
> the second dictionay is for the strings that have the same second
> integer.
> 
> dMap1 = {}
> dMap2 = {}
> 
> # Iterate lists
> for aList in aLists:
> 	
> 	sPass = aList[0]
> 	iValue1 = aList[1]
> 	iValue2 = aPList[2]
> 	
> 	# Map pass name to integers
> 	dMap1.setdefault( iValue1, [] ).append( sPass )
> 	dMap2.setdefault( iValue2, [] ).append( sPass )

If I understand you correctly, you want to group the strings that have both integers the same. Just use the tuple (iValue1, iValue2) as the key in a third dictionary:
        dmap3.setdefault( (iValue1, iValue2), [] ).append( sPass )

Kent

> So far so good, it's working, I end up with this structure:
> 
> dMap1 = {
> 	10 : [ 'Pass1', 'Pass2', 'Pass4' ],
> 	25 : [ 'Pass3', 'Pass5' ] }
> 
> dMap2 = {
> 	100 : [ 'Pass3', 'Pass4' ],
> 	200 : [ 'Pass1', 'Pass2', 'Pass5' ] }
> 
> 
> 3 --
> This is where I'm completely stump.
> I want to consolidate the strings into another dictionary the strings
> that share the same integers, resulting in such a structure:
> 
> dGroups = {
> 	'group0' : [ 'Pass1', 'Pass2' ],	     # 10, 200
> 	'group1' : [ 'Pass4' ],				# 10, 100
> 	'group2' : [ 'Pass3' ],				# 25, 100
> 	'group3' : [ 'Pass5' ],				# 25, 200 }
> 
> However, I have absolutely no idea how to achieve that third dictionary!
> 
> 
> 
> Thanks
> Bernard
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list