[英]How to get rid of multiple nested loops in 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
獲取一張圖像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")
itertools.product
在這里很有幫助。
它可以將嵌套的 for 循環轉換為元組,然后您可以在最終語句中使用這些元組。
你的代碼會是這樣的:
from itertools import product
for imgs, counter, oimgs in product(wire_images, range(0,instance_count,1), images_path):
applyWireAugmentation(oimgs, imgs, wire_dir, odir, 0, dst_dir, counter, "waug")
請記住,如果任何列表(迭代器)為空,則此 for 循環將不會執行,並且它比嵌套 for 循環慢一點,因此您必須犧牲一點性能來提高可讀性。
查看此 Stackoverflow 討論以獲取更多信息
正如其他人建議的那樣,實現這一目標的最佳方法之一是使用生成器,由於沒有可保存在內存中的列表,因此可大大減少內存開銷。
from itertools import product
wire_images = list1... # if possible, try to get them in iterator format as well
images_path = list2... # if possible, try to get them in iterator format as well
instance_count = 10
for imgs, oimgs, counter in product(wire_images, images_path, range(instance_count)):
applyWireAugmentation(oimgs, imgs, wire_dir, odir, 0, dst_dir, counter, "waug")
上述方法在時間與空間和可讀性之間進行權衡。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.