如何循环两次 zip() 函数的一个元素 - Python

Col*_*ain 5 python zip loops resize image

所以这是我的困境......我正在编写一个脚本,它从一个文件夹中读取所有 .png 文件,然后将它们转换为我在列表中指定的多个不同维度。一切正常,除非它在处理一张图像后退出。

这是我的代码:

sizeFormats = ["1024x1024", "114x114", "40x40", "58x58", "60x60", "640x1136", "640x960"]

def resizeImages():

widthList = []
heightList = []
resizedHeight = 0
resizedWidth = 0

#targetPath is the path to the folder that contains the images
folderToResizeContents = os.listdir(targetPath)

#This splits the dimensions into 2 separate lists for height and width (ex: 640x960 adds
#640 to widthList and 960 to heightList
for index in sizeFormats:
    widthList.append(index.split("x")[0])
    heightList.append(index.split("x")[1])

#for every image in the folder, apply the dimensions from the populated lists and save
for image,w,h in zip(folderToResizeContents,widthList,heightList):
    resizedWidth = int(w)
    resizedHeight = int(h)
    sourceFilePath = os.path.join(targetPath,image)
    imageFileToConvert = Image.open(sourceFilePath)
    outputFile = imageFileToConvert.resize((resizedWidth,resizedHeight), Image.ANTIALIAS)
    outputFile.save(sourceFilePath)
Run Code Online (Sandbox Code Playgroud)

如果目标文件夹包含 2 张名为 image1.png,image2.png 的图像,将返回以下内容(为了可视化,我将在下划线后添加应用于图像的尺寸):

image1_1024x1024.png, ........., image1_640x690.png (返回 image1 的所有 7 个不同尺寸)

当我需要它对 image_2 应用相同的转换时,它会停在那里。我知道这是因为 widthList 和 heightList 的长度只有 7 个元素,因此在 image2 轮到它之前退出循环。有什么办法可以为 targetPath 中的每个图像循环遍历 widthList 和 heightList 吗?

Ste*_*nes 4

为什么不简单一点:

for image in folderToResizeContents:
    for fmt in sizeFormats:
        (w,h) = fmt.split('x')
Run Code Online (Sandbox Code Playgroud)

注意:您将覆盖生成的文件,因为您没有更改输出路径的名称。