【发布时间】:2012-10-27 18:26:09
【问题描述】:
我设法将 8 行代码转换为 2 行代码。
第一个列表理解让我得到文件夹,第二个让我得到特定过滤器的文件:
hideTheseFolders=[".thumb",".mayaSwatches","RECYCLER","$AVG"]
fileFilters=["ma","jpg","png","mb",'iff','tga','tif']
newLst=[]
import os
locationTxt="E:\box\scripts"
[newLst.append(each) for each in os.listdir(locationTxt) if os.path.isdir(os.path.join(locationTxt,each)) and each not in hideTheseFolders]
[newLst.append(os.path.basename(os.path.join(locationTxt,each))) for nfile in fileFilters for each in os.listdir(locationTxt) if each.endswith(nfile)]
现在在上面的代码中,最后两行从locationTxt 查找同一目录,这意味着我可能有一种方法可以合并最后两行。有什么建议吗?
【问题讨论】:
-
你为什么要附加到列表理解中的列表?
-
我建议两行就可以了。它们中的每一个都已经发生了很多事情(无论如何都不适合标准的行长),并且每个都做了一些不同的事情。大概你可以对每个理解的结果做
newLst.extend(),而不是在理解中附加到newLst? -
你为什么要把它合并成两行?
-
另外,你知道
os.path.basename(os.path.join(d, f))总是等于os.path.basename(f)吗?
标签: python list python-2.7 list-comprehension