尝试在 Python 中使用列表理解过滤字典列表时出现问题

问题描述

我想从字典列表中过滤,例如对应项目下方的那个,到 fileNametree 的值中为 objectAttribute 并且没有以下值:{ {1}}、green-fieldsNowy-field

yellow-field

从上面的这个列表中,还有一个其他的项目列表,其中有 array = [ {'fileName': 'waterfall_074','objectAttribute': 'black-cliff'},{'fileName': 'waterfall_074','objectAttribute': 'waterfall'},{'fileName': 'opencountry_test_010','objectAttribute': 'red-flower'},'objectAttribute': 'overcast-sky'},{'fileName': 'highway_bost183','objectAttribute': 'cloudy-sky'},'objectAttribute': 'tree'},'objectAttribute': 'road'},{'fileName': 'opencountry_076','objectAttribute': 'yellow-field'},{'fileName': 'opencountry_092','objectAttribute': 'green-field'},{'fileName': 'mountain_086','objectAttribute': 'dusthaze-sky'},'objectAttribute': 'rocky-mountain'},{'fileName': 'ibis_001','objectAttribute': 'black-ibis'},{'fileName': 'bison08','objectAttribute': 'black-bison'},{'fileName': 'volcano_0191',{'fileName': 'horse_097','objectAttribute': 'white-horse'},'objectAttribute': 'green-field'} ] 作为 objectAttribute tree 并且您可以检查此列表中唯一一个没有任何这些值的值:['opencountry_092','horse_097','highway_bost183','bison08']green-fieldsNowy-fieldyellow-field

我想出了以下代码,但它不起作用

highway_bost183

我相信错误在这个条件中......

def busca_images(array):
  print(array)
  arrayFiltered = [n for n in array if 'tree' in n['objectAttribute'] ]
  newSet = set()
  for e in arrayFiltered:
    newSet.add(e['fileName'])
    files = []
  for e in newSet:
    if len([n for n in array if 'green-field' in n['objectAttribute'] or 'sNowy-field' in n['objectAttribute'] or 'yellow-field' in n['objectAttribute'] ]) != 0: files.append(e)
  print(list(files))

解决方法

def busca_images(array):
    has_tree = set()
    has_field = set()
    final = set()
    for each in array:
        if each['objectAttribute'] == 'tree':
            has_tree.add(each['fileName'])
    for each in array:
        if each['fileName'] in has_tree and each['objectAttribute'] in ['green-field','yellow-field','snowy-field']:
            has_field.add(each['fileName'])
    return list(has_tree - has_field)[0]
print(busca_images(array))

这不是最优雅的方法,而且可能有一种更快的方法,无需将列表循环两次。

但很简单:

  • 循环查找树,添加到 has_tree 集合中
  • 再次循环查找字段,添加到 has_fields 集
  • 从 has_tree 中减去 has_field 以获得值

输出:'highway_bost183'

这样做让我想到了。只有一个字典,文件名作为键,然后属性列表作为值不是更好吗?这会让这个过程容易很多。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...