gpt4 book ai didi

Python:如何递归地从嵌套数据结构(列表和字典)中删除无值?

转载 作者:太空狗 更新时间:2023-10-29 17:23:27 25 4
gpt4 key购买 nike

这是一些嵌套数据,包括列表、元组和字典:

data1 = ( 501, (None, 999), None, (None), 504 )
data2 = { 1:601, 2:None, None:603, 'four':'sixty' }
data3 = OrderedDict( [(None, 401), (12, 402), (13, None), (14, data2)] )
data = [ [None, 22, tuple([None]), (None,None), None], ( (None, 202), {None:301, 32:302, 33:data1}, data3 ) ]

目标:删除任何为 None 的键或值(来自“数据”)。如果一个列表或字典包含一个值,它本身就是一个列表、元组或字典,然后递归,以删除 NESTED Nones。

期望的输出:

[[22, (), ()], ((202,), {32: 302, 33: (501, (999,), 504)}, OrderedDict([(12, 402), (14, {'four': 'sixty', 1: 601})]))]

或者更易读,这里是格式化输出:

StripNones(data)= list:
. [22, (), ()]
. tuple:
. . (202,)
. . {32: 302, 33: (501, (999,), 504)}
. . OrderedDict([(12, 402), (14, {'four': 'sixty', 1: 601})])

我会提出一个可能的答案,因为我还没有找到现有的解决方案。我感谢任何替代方案或对现有解决方案的指示。

编辑我忘了提到这必须在 Python 2.7 中工作。我现在不能使用 Python 3。

虽然它值得为其他人发布 Python 3 解决方案。所以请指出您要回答的是哪条 python。

最佳答案

如果您可以假设各个子类的 __init__ 方法具有与典型基类相同的签名:

def remove_none(obj):
if isinstance(obj, (list, tuple, set)):
return type(obj)(remove_none(x) for x in obj if x is not None)
elif isinstance(obj, dict):
return type(obj)((remove_none(k), remove_none(v))
for k, v in obj.items() if k is not None and v is not None)
else:
return obj

from collections import OrderedDict
data1 = ( 501, (None, 999), None, (None), 504 )
data2 = { 1:601, 2:None, None:603, 'four':'sixty' }
data3 = OrderedDict( [(None, 401), (12, 402), (13, None), (14, data2)] )
data = [ [None, 22, tuple([None]), (None,None), None], ( (None, 202), {None:301, 32:302, 33:data1}, data3 ) ]
print remove_none(data)

请注意,这 不会defaultdict 一起使用,因为 defaultdict 接受 __init__ 的附加参数。要使其与 defaultdict 一起工作,需要另一个特殊情况 elif(在常规字典之前)。


另请注意,我实际上构建了 对象。我没有修改旧的。如果您不需要支持修改不可变对象(immutable对象)(如 tuple),则可以修改旧对象。

关于Python:如何递归地从嵌套数据结构(列表和字典)中删除无值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20558699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com