[英]Having 'and' command inside list comprehension
我不明白此源代码在第3行上做了什么, res = [...];
我试图通过在python控制台中使用伪变量和相同的语法格式(例如res = ['raj' / 'esh'];
它给出了错误; 如果使用res = ['raj' and 'esh'];
我总是返回第二个字符串'esh'
,所以我很困惑为什么在行中使用'and'。 语法p / o也使我感到困惑。
def _get_files(parent, p, f, extensions):
p = Path(p) #.relative_to(parent)
res = [p/o for o in f if not o.startswith('.')
and (extensions is None or f'.{o.split(".")[-1].lower()}' in extensions)]
return res
参数p
解析为文件路径(字符串),参数f解析为f = [o.name for o in os.scandir(path) if o.is_file()]
; 该语法行中的path是文件路径。 在理解第3行时,我可以获得任何帮助吗?
这是一个列表理解 。
res = [p/o for o in f if not o.startswith('.')
and (extensions is None or f'.{o.split(".")[-1].lower()}' in extensions)]
是...的语法简写
res = []
for o in f:
if not o.startswith('.') and (extensions is None or f'.{o.split(".")[-1].lower()}' in extensions):
res.append(p/o)
['raj' and 'esh']
是一个单元素数组,其唯一元素是'raj'
和'esh'
; and
如果falsy将评估第一个操作数,而第二个操作数,否则。 由于第一个操作数不是伪造的,因此会得到'esh'
。
代码中的行不是简单的数组,而是一种理解 -基本上是编写构造数组的循环的一种简短方法。 理解的一般语法是
[x for y in z if p]
其中y
将遍历可迭代z
所有元素,检查p
是否为true,如果是,则将x
添加到结果中。 在您的情况下,条件( p
)为
not o.startswith('.')
and
(extensions is None or f'.{o.split(".")[-1].lower()}' in extensions)
对于f
每个元素o
(可能是文件名的可迭代项),如果该条件为true,则结果列表将获得一个元素,该元素由路径p
与文件名o
的串联组成( /
是自然的,如果起初是令人惊讶的视线,路径的串联运算符。)
该片段中出现的不良命名使问题更加复杂。 考虑以下重写:
def _hidden(filename):
return filename.startswith('.')
def _extension(filename):
return '.' + filename.split(".")[-1].lower()
def _extension_ok(filename, allowed_extensions=None):
return allowed_extensions is None
or _extension(filename) in allowed_extensions
def _get_files(parent, path, filenames, allowed_extensions=None):
path = Path(path)
good_paths = [path/filename for filename in filenames
if not _hidden(filename)
and _extension_ok(filename, allowed_extensions)]
return good_paths
现在,它的读法几乎像是英文,并且非常清楚它的作用(唯一的狡猾之处是path/filename
,几乎每个人都可以通过类比UNIX路径来猜测这是什么)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.