【问题标题】:Python Check if any of lists is not empty, and if not do something with corresponding folder that is linked to that listPython 检查任何列表是否不为空,如果不是,则对链接到该列表的相应文件夹执行某些操作
【发布时间】:2022-01-25 01:52:05
【问题描述】:

所以我在这里尝试优化我拥有的一些代码。

代码检查任何列表是否为空,如果不是,则链接到该列表的相应文件夹将保存在外部程序中,因此为了更清楚,这是代码:

if len(match_FIRST)>0 and len(match_SECOND)>0 and len(match_THIRD)>0 and len(match_FOURTH)>0:
  keep = ['FIRST', 'SECOND', 'THIRD', 'FOURTH']
elif len(match_FIRST)>0 and len(match_SECOND)>0 and len(match_THIRD)>0 and len(match_FOURTH)==0:
  keep = ['FIRST', 'SECOND', 'THIRD']
elif len(match_FIRST)>0 and len(match_SECOND)>0 and len(match_THIRD)==0 and len(match_FOURTH)>0:
  keep = ['FIRST', 'SECOND', 'FOURTH']
elif len(match_FIRST)>0 and len(match_SECOND)==0 and len(match_THIRD)>0 and len(match_FOURTH)>0:
  keep = ['FIRST', 'THIRD', 'FOURTH']
elif len(match_FIRST)>0 and len(match_SECOND)>0 and len(match_THIRD)==0 and len(match_FOURTH)==0:
  keep = ['FIRST', 'SECOND']
elif len(match_FIRST)>0 and len(match_SECOND)==0 and len(match_THIRD)>0 and len(match_FOURTH)==0:
  keep = ['FIRST', 'THIRD']
... etc

所以基本上我们将以这种方式保留在 keep= [] 中仅列出链接到非空列表的名称...

你有什么建议可以优化这个的算法,因为现在我只有四个列表,用这种方式手动检查很容易......但需要更好的解决方案......

请指教!

谢谢,

敬礼

【问题讨论】:

标签: python list optimization


【解决方案1】:

您可能只查找列表列表中的filter 非空列表。

做同样事情的另一种方法是使用带有if 的理解作为过滤器:

non_empty_lists = [l for l in lists if len(l) > 0]

例如:

>>> lists = [
...     ['a', 'b', 'c'],
...     [],
...     [],
...     ['d', 'e']
... ]
>>> non_empty_lists = [l for l in lists if len(l) > 0]
>>> non_empty_lists
[['a', 'b', 'c'], ['d', 'e']]

【讨论】:

  • 您实际上不必检查长度。空列表被认为是错误的,因此您可以在推导式末尾使用 if l 进行简化。
  • 我知道,我只是更喜欢更明确的条件。 is not None、len() > 0 等。bool(obj) 对这两个测试没有区别
  • 感谢您的回复,我实际上不仅在尝试过滤非空列表,而且更重要的是相应地填写 keep=[] 列表正确...所以我不需要“列表”空列表,但对应的“名称”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多