dictionary of list from a file

Mirco Wahab wahab at chemie.uni-halle.de
Wed Oct 4 17:43:39 EDT 2006


Thus spoke Paul McGuire (on 2006-10-04 17:34):
> <andrea.spitaleri at gmail.com> wrote in message 
>> this is my first post. my "programming" background is perlish 

> I'll see your perlish line noise, and raise you this obfuscapython:  :)
> 
> data = """\
> 2 1 2 3 4
> 7 7 8 9 10
> 5 1 3 5 7 9
> 2 6 8 10""".split('\n')  # similar to file.readlines(), but easier to paste 
> into news post
> import operator, itertools
> item = operator.itemgetter
> b = dict( (k,sum(map(lambda g:g[1:],grps),[]))
>              for (k,grps) in itertools.groupby( sorted( 
> map(str.split,data) ), item(0) ) )
> for item in sorted(b.items()):
>     print "%s -> %s" % item
> 
> prints:
> 2 -> ['1', '2', '3', '4', '6', '8', '10']
> 5 -> ['1', '3', '5', '7', '9']
> 7 -> ['7', '8', '9', '10']

Hehe! not bad, lets do the reverse in Perl then too ;-)

This should be *one line*, operating on a dictionary %h:

  s/(\d+)\s+(\d+.+)$/push @{$h{$1}},split' ',$2/eg for @data;

(is at least as obfuscated as yours) - add another line for the output:

  print( "$_ => @{$h{$_}} \n") for sort keys %h;

will print (as yours):

     2 => 1 2 3 4 6 8 10
     5 => 1 3 5 7 9
     7 => 7 8 9 10

if your data:

   @data = split"\n",
     '2 1 2 3 4
      7 7 8 9 10'
      5 1 3 5 7 9
      2 6 8 10';

... is fed in. What does all this tell us?
==> Obfuscated Python is *much longer* than
its Perl counterpart ;-)

Regards

Mirco

PS.: I tried to pull the dict in Python
out of a regex search too - but failed.
I'll try tomorrow again ;-)



More information about the Python-list mailing list