MMagician MMagician - 1 year ago 51
Python Question

If condition on list elements within list comprehension

I would like to know whether it's possible to replace this:

results = [x for x in os.listdir(dir_path) if os.path.splitext(x)[1] == ".tif" and "abc" in os.path.splitext(x)[0]]

with something like:

results = [x for x in os.listdir(dir_path) if ext == ".tif" and "abc" in name for ext, name in os.path.splitext(x)]

Thanks for help

Answer Source

You can define name and ext using an inner generator expression:

results = [x for x, name, ext in ((x, *os.path.splitext(x)) for x in os.listdir(dir_path))
             if ext == ".tif" and "abc" in name]

Here, *os.path.splitext(x) unpacks the result of that call to the name and ext variables in the outer list comprehension (only in Python 3). For older versions, you can use (x,) + os.path.splitext(x) instead. Also note that splitext will return a tuple (name, ext), not (ext, name).

Alternatively, instead of using splitext, just check the filename directly, assuming that the part you want to find in the name part can not appear in the extension part of the file name.

results = [x for x in os.listdir(dir_path) if x.endswith(".tif") and "abc" in x]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download