Compairing filenames in a list

Arnaud Delobelle arnodel at gmail.com
Sun Sep 30 18:08:32 EDT 2012


On 30 September 2012 02:27, Kevin Anthony <kevin.s.anthony at gmail.com> wrote:
> I have a list of filenames, and i need to find files with the same name,
> different extensions, and split that into tuples.  does anyone have any
> suggestions on an easy way to do this that isn't O(n^2)?

>>> import os, itertools
>>> filenames = ["foo.png", "bar.csv", "foo.html", "bar.py"]
>>> dict((key, tuple(val)) for key, val in itertools.groupby(sorted(filenames), lambda f: os.path.splitext(f)[0]))
{'foo': ('foo.html', 'foo.png'), 'bar': ('bar.csv', 'bar.py')}

-- 
Arnaud



More information about the Python-list mailing list