[Tutor] Help with lists

Lloyd Kvam pythontutor@venix.com
Sat, 01 Dec 2001 17:00:13 -0500


My understanding:
You have a list of pairs.  You wish to combine those pairs where the first element is the
same into a longer list without duplicating the first element.

One approach is to sort the list based upon the first pair value.  Then step through the
list appending each pair to a new list.  If the last element in the new list matches our
current pair, combine them rather than appending.

In Python:
def combine(listlist,list_a):
   if listlist == []:
     listlist.append(list_a)
   elif listlist[-1][0] == list_a[0]:
     listlist[-1].extend(list_a[1:])
   else:
     listlist.append(list_a)
   return listlist
l1 = [ [1,'a'],[2,'a'],[3,'a'],[2,'b'],[4,'b'],[2,'c']]+[[20, 'A4'],[20, 'A2'],[20, 'E']]
l1.sort()
l2 = reduce(combine, l1, [])
print l2
 >>> [[1, 'a'], [2, 'a', 'b', 'c'], [3, 'a'], [4, 'b'], [20, 'A2', 'A4', 'E']]

reduce is one of the "functional" functions in Python.  The first argument is a function that
will be applied to each element in a list along with the functions prior return value.  The
second argument is the list to be processed.  The optional third argument represents the
initial function return value.

reduce is most commonly used to turn a list into a single value such as by adding up the list
elements.  It is also handy for this kind of list transformation.

Mike Yuen wrote:

> I've got a bit of a problem with lists that I need some help with.
> 
> What I have is a pair of sub-elements (20 and A4) within each element such
> as: 
> [20, A4] <-- We'll call this pair "big element"
> 
> There are over 20000 such big elements.  Not all of them are going to have
> a unique 1st sub-element (ie: the above big element has 20 as it's 1st
> sub element)
> 
> What i'm trying to do is group them all the big elements with
> the same 1st subelements together.
> For example:
> [20, A4]
> [20, A2]
> [20, E] 
> 
> Will make the following big element:
> [20, A4, A2, E]
> 
> Can someone help me out?  I have to stick with lists as the structure
> meaning I can't use tuples or dictionaries.
> 
> Thanks,
> M
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582