分数作为代码中的数组索引,它是如何工作的?

时间:2018-01-15 01:58:37

标签: python arrays indexing fractions

我在Python中理解这段代码(函数)时遇到了困难。 我认为下面的代码将二维图像数组转换为一维缓冲区数组。

但是,在这种情况下,我认为小数可以作为数组索引插入,因为' buf'数组除以8.

(buf[(x + y * self.width) / 8] |= 0x80 >> (x % 8))

有人能解释一下代码是如何工作的,即使它使用小数作为数组索引吗?

def get_frame_buffer(self, image):
    buf = [0x00] * (self.width * self.height / 8)
    # Set buffer to value of Python Imaging Library image.
    # Image must be in mode 1.
    image_monocolor = image.convert('1')
    imwidth, imheight = image_monocolor.size
    if imwidth != self.width or imheight != self.height:
        raise ValueError('Image must be same dimensions as display \
            ({0}x{1}).' .format(self.width, self.height))

    pixels = image_monocolor.load()
    for y in range(self.height):
        for x in range(self.width):
            # Set the bits for the column of pixels at the current position.
            if pixels[x, y] != 0:
                buf[(x + y * self.width) / 8] |= 0x80 >> (x % 8)
    return buf

1 个答案:

答案 0 :(得分:1)

它不是一个小数;当使用Python 2.x时,表达式x将被计算为整数除法,从而产生整数索引 - 只要yself.width23 / 8 # 2.875, but the decimals get truncated => 2 也是整数。仅作为一个例子:

//

顺便说一句,要在Python 3.x中获得相同的结果,您必须使用{% now 'Y' %} 运算符。