python - 如何创建可索引的 map() 或装饰列表 ()?

标签 python python-3.x

我有一长串文件路径,例如:

images = ['path/to/1.png', 'path/to/2.png']

我知道我可以将这个列表包装在一个映射迭代器中,它提供对通过函数映射的列表中的项目的顺序访问,例如:

image_map = map(cv2.imread, images)

然后我可以在遍历列表时延迟加载这些图像文件:

next(image_map)
=> pixels

但我想随机访问原始列表,通过我的 map 函数映射:

image_map[400]
=> pixels

我不想将它转换为列表,因为那样会将我所有的图像加载到内存中,而且它们不适合内存:

# Bad:
list(image_map)[400]

另一种思考方式可能是 list.__getitem__ 上的装饰器。

我知道我可以对列表进行子类化,但我真的希望有一种更简洁的方法。

最佳答案

为什么不直接创建一个访问器类?

class ImageList(object):
    def __init__(self, images):
        self.images = images

    def get_image(self, image_num):
        return cv2.imread(self.images[image_num])

您当然也可以缓冲读取图像。

您还可以提供一个 __getitem__ 方法来进行类似列表的访问:

def __getitem__(self, key):
    return cv2.imread(self.images[key])

用法:

images = ['path/to/1.png', 'path/to/2.png']

image_list = ImageList(images)

image = image_list.get_image(400)    # the same as 
image = image_list[400]              # this

顺便说一下:当然你可以子类化 list 但在 Python 社区中更受青睐。在这里有一个单独的类而不是子类 list 更清楚。过度使用继承也不是最好的风格。

关于python - 如何创建可索引的 map() 或装饰列表 ()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51507869/

相关文章:

python-3.x - 删除黑色背景并使python open cv中的grabcut输出透明

python - 使用 matplotlib.animate 在 python 中对等高线图进行动画处理

python - 如何将列表的值与其索引的幂相加

python-virtualenv : Can't run bash script properly

python - 维吉内尔密码输出包括原始消息

linux - 将 linux 命令转换为 Python 3.5.2

python - 对列表中的列表列表进行排序

Python 从请求响应中跳过标题行

python - 如何判断文件是否是给定目录的后代?

java - 需要专门学习Scheme了解Java和Python