Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

这段Python代码怎么优化?

originData = { 'a': None, 'b': None, 'c': 5, list: [{ 'a': 1, 'b': None}], dict: { 'a': 1, 'b':None}}

def remove_none(data):
  if type(data) == dict:
    for k in list(data.keys()):
      if type(data[k]) == dict or type(data[k]) == list:
        remove_none(data[k])
      elif data[k] == None:
        del data[k]
  elif type(data) == list:
    for v in data:
      if type(v) == dict or type(v) == list:
        remove_none(v)
      elif v == None:
        data.remove(v)

IDE报复杂度过高,请问要如何优化呢?
函数的目的是去除字典originData中的None值,Python版本是3.6


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

如果是我,应该会这么写:

originData = { 'a': None, 'b': None, 'c': 5, 'list': [{ 'a': 1, 'b': None}], 'dict': { 'a': 1, 'b':None}}

def remove_none(data):
    if isinstance(data, dict):
        return {
            k: remove_none(v)
            for k, v in data.items()
            if v is not None
        }
    elif isinstance(data, list):
        return [
            remove_none(v)
            for v in data
            if v is not None
        ]
    else:
        return data

print(remove_none(originData))

不做就地修改,利用字典和列表推荐简化程序处理逻辑。

想知道编写优雅Python代码的秘密?请关注我的专栏:Python源码深度剖析


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...