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

Fractional numbers as array indices in the code, How it works?

我很难理解 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

这不是小数;当使用 Python 2.x 时,表达式 (x + y * self.width) / 8 将被计算为整数除法,从而产生整数索引 - 只要 xyself.width也是整数。举个例子:

23 / 8 # 2.875, but the decimals get truncated
=> 2

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