我的第一次尝试得到了这样的结果:
if [p for p in Path().glob('*.ext')]:
我认为这是低效的,因为整个生成器对象(.glob()
返回的)必须在继续之前由列表理解使用。
我的第二次尝试是手动调用生成器上的.__next__()
并手动捕获StopIteration
,但我不相信这可以在一行中完成:
try:
Path().glob('*.ext').__next__()
except StopIteration:
# no ".ext" files exist here
else:
# at least one ".ext" file exists here
总的来说,我是一个Python noob,我想知道一个单行解决方案是否可能(至少比我第一次尝试的效率更高的解决方案)。
使用任意()
:
if any(p for p in Path().glob('*.ext')):
# ...
或者更简单地说,
if any(Path().glob('*.ext')):
# ...