首页 > 解决方案 > if condition inside lambda while using posix path

问题描述

So, I'm trying to remove hidden files from POSIX PATH i.e.

[PosixPath('/Users/abhimanyuaryan/../imagenette-160/.DS_Store'),
 PosixPath('/Users/abhimanyuaryan/../imagenette-160/train'),
 PosixPath('/Users/abhimanyuaryan/../imagenette-160/val')]

This .DS_Store doesn't make any sense here.

p = Path('/Users/abhimanyuaryan/../imagenette-160/')

I wrote this code. Tried adding if condition at back but I'm confused how do I do that. For a fact I know this code is wrong. Because even if it were a string. .DS_Store is not x[0]

It has to be after last \. I think I might need some regex here to find \. & then exclude it from POSIX PATH

but first I need to correct my if statement which doesn't seem to be correct

Path.ls = lambda x: list(x.iterdir()) if str(x)[0] != '.'

I also saw few labda and if usage questions on SO but didn't understand the correct syntax

标签: python-3.xlambda

解决方案


你还需要有一个else

Path.ls = lambda x: list(x.iterdir()) if str(x)[0] != '.' else None

我用None例如。


推荐阅读