В моей первой версии похоже, что я неправильно истолковал ваш вопрос.Так что, если я правильно понял, вы пытаетесь обработать список файлов, чтобы вы могли легко получить доступ ко всем именам файлов с заданным расширением или ко всем именам файлов с заданной базой ("base" - часть передточка)?
Если это так, я бы порекомендовал такой способ:
from itertools import groupby
def group_by_name(filenames):
'''Puts the filenames in the given iterable into a dictionary where
the key is the first component of the filename and the value is
a list of the filenames with that component.'''
keyfunc = lambda f: f.split('.', 1)[0]
return dict( (k, list(g)) for k,g in groupby(
sorted(filenames, key=keyfunc), key=keyfunc
) )
Например, учитывая список
>>> test_data = [
... exia.frame, exia.head, exia.swords, exia.legs,
... exia.arms, exia.pilot, exia.gn_drive, lockon_stratos.data,
... tieria_erde.data, ribbons_almark.data, otherstuff.dada
... ]
, эта функция выдаст
>>> group_by_name(test_data)
{'exia': ['exia.arms', 'exia.frame', 'exia.gn_drive', 'exia.head',
'exia.legs', 'exia.pilot', 'exia.swords'],
'lockon_stratos': ['lockon_stratos.data'],
'otherstuff': ['otherstuff.dada'],
'ribbons_almark': ['ribbons_almark.data'],
'tieria_erde': ['tieria_erde.data']}
Если вместо этого вы хотите индексировать имена файлов по расширению, небольшая модификация сделает это за вас:
def group_by_extension(filenames):
'''Puts the filenames in the given iterable into a dictionary where
the key is the last component of the filename and the value is
a list of the filenames with that extension.'''
keyfunc = lambda f: f.split('.', 1)[1]
return dict( (k, list(g)) for k,g in groupby(
sorted(filenames, key=keyfunc), key=keyfunc
) )
Единственная разница в строке keyfunc = ...
, где я изменилсяключ от 0 до 1. Пример:
>>> group_by_extension(test_data)
{'arms': ['exia.arms'],
'dada': ['otherstuff.dada'],
'data': ['lockon_stratos.data', 'ribbons_almark.data', 'tieria_erde.data'],
'frame': ['exia.frame'],
'gn_drive': ['exia.gn_drive'],
'head': ['exia.head'],
'legs': ['exia.legs'],
'pilot': ['exia.pilot'],
'swords': ['exia.swords']}
Если вы хотите получить обе эти группы одновременно, я думаю, что было бы лучше избежать понимания списка, потому что это может толькообрабатывать их так или иначе, он не может создать два разных словаря одновременно.
from collections import defaultdict
def group_by_both(filenames):
'''Puts the filenames in the given iterable into two dictionaries,
where in the first, the key is the first component of the filename,
and in the second, the key is the last component of the filename.
The values in each dictionary are lists of the filenames with that
base or extension.'''
by_name = defaultdict(list)
by_ext = defaultdict(list)
for f in filenames:
name, ext = f.split('.', 1)
by_name[name] += [f]
by_ext[ext] += [f]
return by_name, by_ext