如何解决尝试在 Python 中使用列表理解过滤字典列表时出现问题
我想从字典列表中过滤,例如对应项目下方的那个,到 fileName
在 tree
的值中为 objectAttribute
并且没有以下值:{ {1}}、green-field
或 sNowy-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-field
或 sNowy-field
是 yellow-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'
这样做让我想到了。只有一个字典,文件名作为键,然后属性列表作为值不是更好吗?这会让这个过程容易很多。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。