python - 使用过滤器和关联列表过滤图像列表

标签 python

我有一个作业,其中一部分要求定义一个 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/

相关文章:

python - 大型项目中选择Scons还是Waf

python - 我试图用子弹击中永久 'kill' 目标,但在使用 '.kill()' (PYGAME) 后它们重新出现

python - 使用 Python 成像确定锅中咖啡的高度

python - 在 multiprocessing.Process() 中调用 subprocess.Popen() 时管道损坏

python - 使用 **dict 时忽略无效的关键字参数

python - 寻找 OpenAi 的 Codex,如开源沙盒 Playground

python - Django 表单预览 : Save form data to database

Python Tkinter 类结构实践

python 集合与元组查找。是元组 O(1) 中的查找?

python - long double returns 和 ctypes