最直接的方法是将一个整数元组乘以一个浮点数,然后得到一个整数元组

2024-09-19 20:59:28 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我将一个整数元组重缩放到另一个整数元组的步骤。有更好的办法吗?你知道吗

size_tup = tuple([int(round(s*shrink)) for s in size])

我需要使用Image模块调整图像大小,因为这需要tupleints。举个例子,如果我想把一个图像的大小调整50%,我会这样做

size = .5     
size_tup = tuple([int(round(s*shrink)) for s in size])   
im = im.resize(size_tup, Image.ANTIALIAS)

所以我只处理长度为2的元组。我最关心的是代码的简单性,因为上面的内容似乎有些过分了。你知道吗


Tags: in图像imageforsize步骤整数int
2条回答

我想类似的东西会对你有帮助。你知道吗

map(lambda x: x * n, tuple)

根据map函数的定义:

map(function, iterable, ...) Apply function to every item of iterable and return a list of the results

在代码中,您将创建一个列表,然后将其转换为元组。使用map函数来延迟列表的计算(在python3中)。你知道吗

size_tup = tuple(
            map(int, #this function calls int on each element
                map(round, #this function calls round on each element
                    map(lambda x : x * shrink, #this function multplies each element by shrink
                        size))))

根据注释,您也可以这样做(删除[]):

tuple(int(round(s*shrink)) for s in size)

相关问题 更多 >