消除由列表和数组组成的python dict中的空值

2024-03-29 05:57:39 发布

您现在位置: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


3条回答

检查空列表的常用方法是检查len(list)。所以假设你的dict()看起来是这样的

myDict = {
  1: [1,2,3],
  2: [],
  3: np.array([[1,2],[3,4],[5,6]])
}

您的列表可能如下所示

res = {k:v for k,v in myDict.items() if len(v)}

注意听写理解中的len(v)

我认为您使这一步变得过于复杂(并且没有包含完整的示例!)

下面的示例创建一个新的dict res,其中test_dict的所有值都具有非空值。我在这里使用了len(),因为这对列表和nd数组都有效。对于just list,我将省略对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(),您将查找包含至少一个truthy项的列表的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)}

@雅各布的回答很好,但效率很低

相反,您可以利用内置的filter()方法过滤掉空字典,并使用dict()方法而不是使用dict理解:

res = filter(None, (dict(i for i in sub.items() if len(i[1])) for sub in test_list))

相关问题 更多 >