我有一个文件夹名称列表作为一维数组:即:
folderList=['A1_001', 'A1_002', 'A1_003', 'A1_004',
'A2_001', 'A2_002', 'A2_003', 'A2_004',
'A3_001', 'A3_002', 'A3_003', 'A3_004']
并希望按前两个字符对列表进行分组,如“A1”、“A2”和“A3”。我认为这应该通过 groupby 完成,但我的代码不起作用
sectionName=[] #to get the first two characters of each element into a new list
for file in folderList:
sectionName.append(file.split('_')[0])
for key, group in groupby(folderList,sectionName):
print key
for record in group:
print record
我得到了一个错误:
for key, group in groupby(folderList,sectionName):
TypeError: 'list' object is not callable
我想要得到的是这样的结果:
A1
['A1_001', 'A1_002', 'A1_003', 'A1_004']
A2
['A2_001', 'A2_002', 'A2_003', 'A2_004']
A3
['A3_001', 'A3_002', 'A3_003', 'A3_004']
我认为该groupby
功能需要第二个输入才能成为 keyfunction,但到目前为止未能实现sectionName
into keyfunction。如果您能提供帮助,请提前致谢。