python - 消除由列表和数组组成的python dict中的空值
问题描述
我想从 dict 中消除所有空值,其值是列表和 nd 数组的混合。所以我尝试了:
res = [ele for ele in ({key: val for key, val in sub.items() if val} for sub in test_list) if ele]
但我得到了错误
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). And if I try:
AttributeError: 'list' object has no attribute 'any'
我得到错误
AttributeError: 'list' object has no attribute 'any'
所以我想知道是否有更通用的方法来删除 python 中的空值dict
。
解决方案
我认为您使这一步比必要的复杂(并且不包括完整的示例!)
下面的示例创建一个新的字典res
,其中的所有值test_dict
都具有非空值。我len()
在这里使用,因为它适用于列表和 nd 数组。对于列表,我会省略调用len()
并仅使用val
.
test_dict = {1: [], 2: [1,2,3], 3: [4,5,6]}
res = {key: val for key, val in test_list.items() if len(val)}
如果您想使用 any(),您会发现 dict 值是包含至少一个真实项目的列表:
test_dict = {1: [], 2: [1,2,3], 3: [4,5,6]}
res = {key: val for key, val in test_list.items() if any(val)}
推荐阅读
- xml - 如何更改浮动操作按钮的背景颜色
- node.js - 詹金斯构建失败 - 错误:未找到:制作
- c++ - 虚幻引擎的 Actor 类的 OnConstruction() 方法未正确执行
- operating-system - 开发操作系统、用户模式、中断和系统调用
- serenity-bdd - 在 serenity.properties 文件中提及您想使用哪个浏览器运行测试就足够了吗?
- python - Aiohttp 异步会话请求
- yaml - Jekyll / Liquid:将数组传递到包含和循环中
- python - Scrapy-splash 没有名为 scrapy_splash 的模块。破点
- python - 来自 python NoBrokersAvailable 的 Kafka 消费者
- concordion - Concordion 无法复制资源(突然)