python - 如何摆脱 python 中的多个嵌套循环

标签 python

这是我的代码;

instance_count = 10
for imgs in wire_images:
    for counter in range(0, instance_count, 1):
        for oimgs in images_path:
            applyWireAugmentation(oimgs, imgs, wire_dir, odir, 0, dst_dir, counter, "waug")


def applyWireAugmentation(img, wire_img,wdir, odir, theata,dst_path, counter, index):

    src_im = Image.open(wdir+wire_img).convert("LA")
    dst_im = Image.open(odir+img)
    w,h = dst_im.size
    angle = theata
    size = 200, h

    x = random.randint(0,w)
    y = 0
    im = src_im.convert('RGBA')
    rot = im.rotate( angle, expand=1 ).resize(size)
    dst_im.paste( rot, (x, y), rot )
    dst_im.save(dst_path+"/"+img.replace(".png","")+"-"+index+"-"+str(counter)+".png")

wire_images 包含文件夹中的所有图像文件。 images_path 将所有图像文件放在另一个文件夹中。我需要从 wire_images 中获取一张图像并将其应用于 oimgs instance_count 次(在本例中为 10 次)。是否有任何圆滑的 pythonic 方法来摆脱这些循环或使其更快?

最佳答案

你之前可以生成所有可能的组合,但我不确定它是否更好:

import itertools
comb = itertools.product(wire_images, images_path, range(0,instance_count,1))

for imgs, oimgs, counter in comb:
    applyWireAugmentation(oimgs, imgs,wire_dir,odir, 0, dst_dir, counter,  "waug")

关于python - 如何摆脱 python 中的多个嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60163249/

相关文章:

python - 如何从 setup.py 判断模块是否以可编辑模式安装

python - python 中 qq-plot(或 probplot)的逐点置信度包络线

python - 使用 Python 导入模块(PyCogent)

python - 如何使用 FFT 查找方波的频率

Python MD5 哈希计算更快

python - 如何使用 Flask-SQLAlchemy 生成类似 post_save 信号的 Django?

python - 我可以用数据框一次替换一些值吗?

python - 错误: [Errno 10054] An existing connection was forcibly closed by the remote host

python - 使用回归模型进行预测的方法

python - 在python中对一个列表进行排序以匹配另一个列表