简体   繁体   中英

Modify list element without list comprehension in Python

I use this function to extract rgb values from images:

def get_rgb_and_rgba_values_for_next_three_pixels(image_data, pixel_type):
    if pixel_type == "rgb":
        rgba_values = []
        rgb_values = [image_data.next()[:3], image_data.next()[:3], image_data.next()[:3]]
    else:
        rgba_values = [image_data.next()[:4], image_data.next()[:4], image_data.next()[:4]]
        rgb_values = [rgba_values[0][:3], rgba_values[1][:3], rgba_values[2][:3]]
    return [rgba_values, rgb_values]

Output:

[[(255, 255, 255), (255, 255, 255), (255, 255, 255)], [(255, 255, 255, 0), (255, 255, 255, 0), (255, 255, 255, 0)]]

then I use this function to change all lsbs to 0:

def set_least_significant_bit_to_zero(rgb_values):
    return [value & ~1 for value in rgb_values[0][:3] + rgb_values[1][:3] + rgb_values[2][:3]]

Output:

[254, 254, 254, 254, 254, 254, 254, 254, 254]

My question is: how do I achieve exactly the same thing but without using list comprehensions in second function?

There's no reason to avoid the list comprehension - it is readable, Pythonic, and efficient - however, if you insist you can construct a result list by iterating over the values, appending the new value to the result list, and then returning the result from the function:

def set_least_significant_bit_to_zero(rgb_values):
    result = []
    for value in rgb_values[0][:3] + rgb_values[1][:3] + rgb_values[2][:3]:
        result.append(value & ~1)
    return result

You could also use itertools.chain() to make the for loop iterable:

import itertools

def set_least_significant_bit_to_zero(rgb_values):
    result = []
    for value in itertools.chain(rgb_values[0][:3], rgb_values[1][:3], rgb_values[2][:3]):
        result.append(value & ~1)
    return result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM