我在 python 中有一个由各种文件名组成的字符串列表,如下所示(但更长):
all_templates = ['fitting_file_expdisk_cutout-IMG-HSC-I-18115-6,3-OBJ-NEP175857.9+655841.2.feedme', 'fitting_file_sersic_cutout-IMG-HSC-I-18115-3,3-OBJ-NEP180508.6+655617.3.feedme', 'fitting_file_sersic_cutout-IMG-HSC-I-18115-1,8-OBJ-NEP180840.8+665226.2.feedme', 'fitting_file_sersic_cutout-IMG-HSC-I-18115-6,7-OBJ-NEP175927.6+664230.2.feedme', 'fitting_file_expdisk_cutout-IMG-HSC-I-18114-0,5-OBJ-zsel56238.feedme', 'fitting_file_devauc_cutout-IMG-HSC-I-18114-0,3-OBJ-NEP175616.1+660601.5.feedme', 'fitting_file_sersic_cutout-IMG-HSC-I-18115-6,4-OBJ-zsel56238.feedme']
我想为具有相同对象名称(以 开头OBJ-和结尾的子字符串)的元素创建多个较小的列表.feedme。所以我有一个这样的列表:
obj1 = ['fitting_file_expdisk_cutout-IMG-HSC-I-18114-0,5-OBJ-zsel56238.feedme', 'fitting_file_sersic_cutout-IMG-HSC-I-18115-6,4-OBJ-zsel56238.feedme'],
等等其他匹配的“对象”。实际上,我有 900 多个独特的“对象”,而原始列表all_templates有 4000 多个元素,因为每个对象都有 3 个或更多单独的模板文件(它们都以随机顺序出现)。所以最后我想要超过 900 个列表(每个对象一个)。我怎样才能做到这一点?
编辑:这是我尝试过的,但它为我提供了每个子列表中所有原始模板文件名的列表(对于一个对象名称,每个文件名都应该是唯一的)。
import re
# Break up list into multiple lists according to substring (object name)
obj_list = [re.search(r'.*(OBJ.+)\.feedme', filename)[1] for filename in all_template_files]
obj_list = list(set(obj_list)) # create list of unique objects (remove duplicates)
templates_objs_sorted = [[]]*len(obj_list)
for i in range(len(obj_list)):
for template in all_template_files:
if obj_list[i] in template:
templates_objs_sorted[i].append(template)
胡说叔叔
慕神8447489
相关分类