groupBy in D?

Russel Winder via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Mar 14 09:35:24 PDT 2017


On Tue, 2017-03-14 at 16:12 +0100, Daniel Kozak via Digitalmars-d-learn 
wrote:
> […]
> 
> Can you post some example? Maybe in python, kotlin whatever so I can 
> better understand what you want

In my head I had something such as Groovy's

  files = new File('test-data').listFiles().collect{it.name}
  println files.groupBy({ it.split('_')[0]})


The I remembered that itertools.groupby in Python behaves like D's
std.algorithm.iteration.chunkBy and not like Groovy's groupBy. So in
Python you have to hack it with:

  from collections import defaultdict
  from os import listdir
  from os.path import isfile, splitext

  result = defaultdict(list)
  files = tuple((item.split('_')[0], item) for item in listdir('test-data') if isfile('test-data/' + item))
  for p, v in files:
    result[p] += [v]
  print(result)

Given the seeming lack of Groovy-style groupBy, I guess I will have to
do something Python-like in D. Except I am not sure D has an equivalent
of defaultdict.

-- 
Russel.
=============================================================================
Dr Russel Winder      t: +44 20 7585 2200   voip: sip:russel.winder at ekiga.net
41 Buckmaster Road    m: +44 7770 465 077   xmpp: russel at winder.org.uk
London SW11 1EN, UK   w: www.russel.org.uk  skype: russel_winder
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: This is a digitally signed message part
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20170314/72bfdbf2/attachment.sig>


More information about the Digitalmars-d-learn mailing list