简体   繁体   English

Python 检查是否有任何列表不为空,如果不为空,则对链接到该列表的相应文件夹执行某些操作

[英]Python Check if any of lists is not empty, and if not do something with corresponding folder that is linked to that list

So here I am trying to optimize some code I have.所以在这里我试图优化我拥有的一些代码。

Code checks if any of lists is empty, and if it is not, corresponding folder that is linked to that list will be saved in external program, so to make it more clear this is code:代码检查任何列表是否为空,如果不是,则链接到该列表的相应文件夹将保存在外部程序中,因此为了更清楚,这是代码:

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

So basically we will in this way keep in keep= [] list only names that are linked to lists that are not empty...所以基本上我们将以这种方式保留 keep= [] 仅列出链接到非空列表的名称...

What do you suggest any algorithm that can optimize this since now when I have only four lists it is easy to manually check it this way... but better solution is needed...你有什么建议可以优化这个的算法,因为现在我只有四个列表,很容易手动检查它......但是需要更好的解决方案......

Please advice!请指教!

Thanks,谢谢,

Salute礼炮

You're probably looking to filter only non-empty lists from your list of lists.您可能希望仅从列表列表中过滤非空列表。

Another way to do the same thing is to use a comprehension with if as filter:做同样事情的另一种方法是使用带有if作为过滤器的理解:

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

For example:例如:

>>> 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']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM