Simple list problem that's defeating me!

Sion Arrowsmith sion at viridian.paintbox
Thu Jun 24 05:24:07 EDT 2010


Mark Lawrence  <breamoreboy at yahoo.co.uk> wrote:
>On 22/06/2010 15:06, Neil Webster wrote:
>> I have a list of lists such as [[a,2,3,4],[b,10,11,12], [a,2,3,4]].  I
>> need to combine the two lists that have the same first character in
>> this example 'a'.  In reality there are 656 lists within the list.
>> [ ... ]
>My simplistic approach.
>
>Sort the list (this happens in place).
>Use the itertools groupby function to place everything together, see
>http://docs.python.org/library/itertools.html?highlight=groupby#itertools.groupby
>Combine the lists in the groups.

I suspect the following is a more efficient way of acheiving the grouping:

d = collections.defaultdict(list)
for a in L:
    d[a[0]].append(a[1:])

-- 
\S

   under construction




More information about the Python-list mailing list