I\'m doing a script to save a read path in sublist. Let\'s suppose I have 400 file paths saved in a list, every path has the specific syntax Ci_whaterver.csv
, then
If pathlist
is pre-sorted, you can use the following code based on the itertools.groupby.
from itertools import groupby
pathlist=['Cn_01.csv', 'C1_02.csv', 'C9_01.csv', 'C9_02.csv', 'Ca_01.csv', 'C9_03.csv', 'Ca_02.csv', 'C1_01.csv', 'Cn_02.csv']
pathlist.sort()
groupedfilenames = (list(g) for _, g in groupby(pathlist, key=lambda a: a[:2]))
print(list(groupedfilenames))
Output:
[['C1_01.csv', 'C1_02.csv'], ['C9_01.csv', 'C9_02.csv', 'C9_03.csv'], ['Ca_01.csv', 'Ca_02.csv'], ['Cn_01.csv', 'Cn_02.csv']]