给定一个字典:
mydict = {"g18_84pp_2A_MVP1_GoodiesT0-HKJ-DFG_MIX-CMVP1_Y1000-MIX.txt" : 0,
"g18_84pp_2A_MVP2_GoodiesT0-HKJ-DFG_MIX-CMVP2_Y1000-MIX.txt" : 1,
"g18_84pp_2A_MVP3_GoodiesT0-HKJ-DFG_MIX-CMVP3_Y1000-MIX.txt" : 2,
"g18_84pp_2A_MVP4_GoodiesT0-HKJ-DFG_MIX-CMVP4_Y1000-MIX.txt" : 3,
"g18_84pp_2A_MVP5_GoodiesT0-HKJ-DFG_MIX-CMVP5_Y1000-MIX.txt" : 4,
"g18_84pp_2A_MVP6_GoodiesT0-HKJ-DFG_MIX-CMVP6_Y1000-MIX.txt" : 5,
"h18_84pp_3A_MVP1_GoodiesT1-HKJ-DFG-CMVP1_Y1000-FIX.txt" : 6,
"g18_84pp_2A_MVP7_GoodiesT0-HKJ-DFG_MIX-CMVP7_Y1000-MIX.txt" : 7,
"h18_84pp_3A_MVP2_GoodiesT1-HKJ-DFG-CMVP2_Y1000-FIX.txt" : 8,
"h18_84pp_3A_MVP3_GoodiesT1-HKJ-DFG-CMVP3_Y1000-FIX.txt" : 9,
"p18_84pp_2B_MVP1_GoodiesT2-HKJ-DFG-CMVP3_Y1000-FIX.txt" : 10}
- 从第一个 - 之前提取公共部分
g18_84pp_2A_MVP1_GoodiesT0
。 - 在第一组中找到特定单词
MIX
并添加一个_MIX
。 - 假设您可以根据
myDict
中的MIX
或FIX
将其分类为两组,那么最终的输出字典应该是:
OutputNameDict= {"g18_84pp_2A_MVP_GoodiesT0_MIX" : 0,
"h18_84pp_3A_MVP_GoodiesT1_FIX" : 1,
"p18_84pp_2B_MVP_FIX": 2}
2. 解决方案
2.1 提取公共部分
可以使用 split()
函数按 -
分割字符串,然后取第一个部分作为公共部分。
def extract_common_part(string):
parts = string.split('-')
return parts[0]
2.2 查找特定单词并添加后缀
可以使用 in
运算符检查字符串中是否存在特定单词,然后使用 replace()
函数添加后缀。
def add_suffix(string, word, suffix):
if word in string:
return string.replace(word, word + suffix)
else:
return string
2.3 分类并生成输出字典
根据 myDict
中的 MIX
或 FIX
将其分类为两组,然后使用 extract_common_part()
和 add_suffix()
函数生成输出字典。
def generate_output_dict(mydict):
output_dict = {}
for key, value in mydict.items():
common_part = extract_common_part(key)
if 'MIX' in key:
output_dict[common_part + '_MIX'] = value
else:
output_dict[common_part + '_FIX'] = value
return output_dict
2.4 代码示例
mydict = {"g18_84pp_2A_MVP1_GoodiesT0-HKJ-DFG_MIX-CMVP1_Y1000-MIX.txt" : 0,
"g18_84pp_2A_MVP2_GoodiesT0-HKJ-DFG_MIX-CMVP2_Y1000-MIX.txt" : 1,
"g18_84pp_2A_MVP3_GoodiesT0-HKJ-DFG_MIX-CMVP3_Y1000-MIX.txt" : 2,
"g18_84pp_2A_MVP4_GoodiesT0-HKJ-DFG_MIX-CMVP4_Y1000-MIX.txt" : 3,
"g18_84pp_2A_MVP5_GoodiesT0-HKJ-DFG_MIX-CMVP5_Y1000-MIX.txt" : 4,
"g18_84pp_2A_MVP6_GoodiesT0-HKJ-DFG_MIX-CMVP6_Y1000-MIX.txt" : 5,
"h18_84pp_3A_MVP1_GoodiesT1-HKJ-DFG-CMVP1_Y1000-FIX.txt" : 6,
"g18_84pp_2A_MVP7_GoodiesT0-HKJ-DFG_MIX-CMVP7_Y1000-MIX.txt" : 7,
"h18_84pp_3A_MVP2_GoodiesT1-HKJ-DFG-CMVP2_Y1000-FIX.txt" : 8,
"h18_84pp_3A_MVP3_GoodiesT1-HKJ-DFG-CMVP3_Y1000-FIX.txt" : 9,
"p18_84pp_2B_MVP1_GoodiesT2-HKJ-DFG-CMVP3_Y1000-FIX.txt" : 10}
output_dict = generate_output_dict(mydict)
print(output_dict)
输出结果:
{'g18_84pp_2A_MVP_GoodiesT0_MIX': 0, 'h18_84pp_3A_MVP_GoodiesT1_FIX': 1, 'p18_84pp_2B_MVP_FIX': 2}