在Python中修改没有列表理解的列表元素

时间:2017-05-14 23:58:04

标签: python list

我使用此函数从图像中提取rgb值:

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]

输出:

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

然后我使用此函数将所有lsbs更改为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]]

输出:

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

我的问题是:如何在第二个函数中不使用列表推导而实现完全相同的事情?

1 个答案:

答案 0 :(得分:0)

没有理由避免列表理解 - 它是可读的,Pythonic和高效的 - 但是,如果你坚持你可以通过迭代值来构造结果列表,将新值附加到结果列表,然后返回函数的结果:

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

您还可以使用itertools.chain()使for循环可迭代:

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