我有一个作业,其中一部分要求定义一个 process_filter_description。基本上我有一个要过滤的图像列表:
images = ["1111.jpg", "2222.jpg", "circle.JPG", "square.jpg", "triangle.JPG"]
现在我有了一个可以用来过滤图像的关联列表:
assc_list = [ ["numbers", ["1111.jpg", "2222.jpg"]] , ["shapes", ["circle.JPG", "square.jpg", "triangle.JPG"]] ]
我可以使用过滤器描述来选择要应用过滤器的关联列表(关键字用冒号括起来):
f = ':numbers:'
我不太确定如何开始。用语言来说,我至少可以这样想:
- 过滤器为“:numbers:”
- 将图像的每个术语与关联列表中与数字关联的每个术语进行比较。
- 如果术语匹配,则将术语附加到空列表。
现在我只是想让我的代码只打印数字关联列表中的术语,但它会打印出所有这些术语。
def process_filter_description(f, images, ia):
return_list = []
f = f[1:-1]
counter = 0
if f == ia[counter][0]:
#print f + ' is equal to ' + ia[counter][0]
for key in ial:
for item in key[1]:
#print item
#return_list.append(item)
return return_list
最佳答案
不使用“关联列表”,使用字典怎么样?
filter_assoc = {'numbers': ['1111.jpg', '2222.jpg'] ,
'shapes': ['circle.JPG', 'square.jpg', 'triangle.JPG']}
现在,只需查看每组中有哪些图像:
>>> filter_assoc['numbers']
['1111.jpg', '2222.jpg']
>>>
>>> filter_assoc['shapes']
['circle.JPG', 'square.jpg', 'triangle.JPG']
您的处理功能将变得非常简单:
def process_filter_description(filter, association):
return association[filter[1:-1]]
<小时/>
我只是在这里大声思考,所以这就是我用作执行字典任务的函数:
def process_filter_description(index, images, association):
return_list = []
index = index[1:-1]
for top_level in association:
if top_level[0] == index:
for item in top_level[1]:
return_list.append(item)
break
return return_list
关于python - 使用过滤器和关联列表过滤图像列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7949383/