toy list processing problem: collect similar terms

Bakul Shah usenet at
Mon Sep 27 00:10:46 CEST 2010

On 9/25/10 9:05 PM, Xah Lee wrote:
> here's a interesting toy list processing problem.
> I have a list of lists, where each sublist is labelled by
> a number. I need to collect together the contents of all sublists
> sharing
> the same label. So if I have the list
> ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> r) (5 s t))
> where the first element of each sublist is the label, I need to
> produce:
> output:
> ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
> anyone care to give a solution in Python, Perl, javascript, or other
> lang? am guessing the scheme solution can be much improved... perhaps
> using some lib but that seems to show scheme is pretty weak if the lib
> is non-standard.

In Q (from[1]:

x:((0; "a"; "b");(1; "c"; "d");(2; "e"; "f");(3; "g"; "h");(1; "i"; "j")
    (2; "k"; "l");(4; "m"; "n");(2; "o"; "p");(4; "q"; "r");(5; "s"; "t"))
f:{each [,/] each [each [1 _]] x @ value group x[;0]}
f x



Note that this is actually a pretty general solution in that *all*
the functions used in it operate on a variety of types.
- The label could be anything, not just an integer.
- What follows a label can be a list of anything.
- Everything, except for = (the group function), has to do with
   *shaping* the output in the way you want. It is all basically
   cut-n-paste or pulling apart your Lego blocks and constructing
   a new toy from them! And most languages are really poor at that.
   *This* is why proponents of various languages should pay attention
   to such problems.

[1] In k3 (an older language from that you may be able to find
     online), x is the same but f is as follows:


More information about the Python-list mailing list