我为我的目的创建了一种数据结构,它是一个简单的字典,其中包含值列表作为数据:
{'Procedure_name': ('compound', 'hardware', 'tempval', 'colorval', 'energyval'), .....}
想象一系列的步骤,你在其中混合两种化合物,并记录温度变化、电位能、颜色差异等,这就是词典中每个条目代表的内容。
实现一个过滤器的最佳方式是什么?这是我想要实现的例子。我的过滤器大多会尝试使用少量参数(例如化合物、硬件),可以单独使用或组合使用。
dataset = {'Att1_Cl': ('carb', 'Spectrometer_v1', '33', '0.25', '445'),
'Att1_Na': ('carb', 'Spectrometer_v1', '34.2', '0.21', '401'),
'Att1_Si': ('alc', 'Photometer_V2', '32.1', '0.43', '521'),
'Att1_Cr': ('carb', 'Photometer_V3', '32.5', '0.49', '511')}
def filter_data(filter)
....
return filtered_data # the entry from the dictionary that satisfy the condition
作为输出示例:
print (filter_data (['carb']))
Att1_Cl
('carb', 'Spectrometer_v1', '33', '0.25', '445')
Att1_Na
('carb', 'Spectrometer_v1', '34.2', '0.21', '401')
Att1_Cr
('carb', 'Photometer_V3', '32.5', '0.49', '511')
print (filter_data (['Spectrometer_v1']))
Att1_Cl
('carb', 'Spectrometer_v1', '33', '0.25', '445')
Att1_Na
('carb', 'Spectrometer_v1', '34.2', '0.21', '401')
print (filter_data (['carb', 'Photometer_V3']))
Att1_Cr
('carb', 'Photometer_V3', '32.5', '0.49', '511')
我在考虑使用列表作为可选参数,并比较数据集中的每个条目;但我找不到一个有效的方法来完成这个任务。以下是我的第一种尝试:
def filter_data(filter):
for procedure in dataset:
single_dataset = dataset[procedure]
if filter in single_dataset:
print(procedure)
print(single_dataset)
如果我只有一个条目,这个方法是有效的,但如果我的筛选列表里有多个条目,我就不得不对数据集进行多次操作,这既不高效也不可扩展,万一我需要向我的数据结构添加更多参数呢。 我心中还有另一种选择,那就是保存预制的筛选器,并通过传递给函数的筛选参数来调用它们,但从代码维护的角度来看,这真是噩梦一般的存在,因为每次更改筛选器时都必须硬编码。