Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I rewrite this for loop in list comprehensions

I got a "for loop" like this:

for dirctory in dirs:
    for item in os.walk(dirctory):
        for i in item[2]:
            i = os.path.join(item[0], i)
            if is_image(i):
                images.append(i)

And I tried to rewrite it into list comprehensions, I tried this:

images.extend(filter(is_image, [item[0]+i for i in item[2] for item in os.walk(dirctory)]))

It says UnboundLocalError: local variable 'item' referenced before assignment

So I tried this:

images.extend(filter(is_image, [(item[0]+i for i in item[2]) for item in os.walk(dirctory)]))

It says TypeError: coercing to Unicode: need string or buffer, generator found

I use Python 2.7.4 in OS X.

like image 770
Kane Blueriver Avatar asked Jan 01 '26 00:01

Kane Blueriver


2 Answers

Try this:

[os.path.join(item[0], i) for directory in dirs for item in os.walk(dirctory) for i in item[2] if is_image(os.path.join(item[0], i))]
like image 105
K DawG Avatar answered Jan 03 '26 13:01

K DawG


def check_image(directory, file_name):
    file_name = os.path.join(directory, file_name)
    return is_image(file_name), file_name

[full_path
     for current_dir in dirs
     for parent_dir, _, files in os.walk(current_dir)
     for current_file in files
     for isimage, full_path in [check_image(parent_dir, current_file)]
         if isimage]

The check_image function is there to avoid applying os.path.join twice.

like image 30
thefourtheye Avatar answered Jan 03 '26 12:01

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!