简体   繁体   English

在Python中修改列表元素而无需列表理解

[英]Modify list element without list comprehension in Python

I use this function to extract rgb values from images: 我使用此功能从图像中提取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]

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

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: 没有理由避免列表理解-它是可读的,Python式的和高效的-但是,如果您坚持可以通过遍历值,将新值附加到结果列表然后从中返回结果来构造结果列表,功能:

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: 您还可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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