删除所有元素都不为空的嵌套列表

2024-04-23 09:37:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一系列的列表(在字典中),我想删除任何只有None作为元素的列表。但是,列表有各种不同的格式,例如

x=[None,[None],[None]]
x=[None,None,None]
x=[None,[None,None],[None,None]]

其中任何None都可以替换为一个值。你知道吗

任何示例都可以使用以下词典:

dict={"x1": [None,None,None],"x2": [None,[None],[None]], "x3": [None,[1],[0.5]],
      "x4":[None,[None,None],[None,None]],"x5":[None,[180,-360],[90,-180]]}

在本例中,我希望保留(key,value)"x3""x5",因为它们包含的值不是全部None,而是要删除"x1""x2""x4",从而返回:

dict={"x3": [None,[1],[0.5]], "x5":[None,[180,-360],[90,-180]]}

字典中各种列表(x)的简单列表理解,例如

any(e is not None for e in x)

[None]项读取为not None,并返回True。你知道吗

如何确定哪些列表实际包含值而不是[None]元素。我已经研究了删除方括号的选项,例如使用itertools,如这里所建议的[Remove brackets from list in Python],但是这些都依赖于列表中的所有元素以相同的方式格式化,而我的格式是混合的。我无法更改格式,因为软件中的其他地方需要此格式。你知道吗


Tags: innone元素示例列表字典格式not
3条回答

您可以编写一个自定义递归函数来检查嵌套列表的所有元素是否都是None。你知道吗

def is_none(a):
    return all(x is None if not isinstance(x, list) else is_none(x) for x in a)

my_dict = {"x1": [None, None, None],
           "x2": [None, [None], [None]],
           "x3": [None, [1], [0.5]],
           "x4": [None, [None, None], [None, None]],
           "x5": [None, [180, -360], [90, -180]]}

new_dict = {k: v for k, v in my_dict.items() if not is_none(v)}
print(new_dict)
# {'x3': [None, [1], [0.5]], 'x5': [None, [180, -360], [90, -180]]}

这种解决方案在性质上与Keyur Potdar类似,但它适用于各种容器,不仅适用于list

my_dict = {
    "x1": [None, None, None],
    "x2": [None, [None], [None]],
    "x3": [None, [1], [0.5]],
    "x4": [None, [None, None], [None, None]],
    "x5": [None, [180, -360], [90, -180]],
}

def all_None(val):
    # Check for None
    if val is None:
        return True
    # val is not None
    try:
        # val may be a container
        return all(all_None(el) for el in val)
    except:
        # val is neither None nor a container
        return False

my_dict_filtered = {key: val for key, val in my_dict.items() if not all_None(val)}
print(my_dict_filtered)

根据Benjamin的注释,如果list_input中的所有嵌套列表都包含相同的值val_to_check,则此函数应返回True,否则返回False:

def check_val(list_input, val_to_check):
    for elem in list_input:
        if isinstance(elem, list):
            if check_val(elem, val_to_check) == False:
                return False
        else:
            if elem != val_to_check:
                return False
    return True

相关问题 更多 >