以下两个循环结构基本相同。我只是不知道如何在第一个语法中插入两个变量 start = start+2end = end+2 。谢谢

第一个构造(列表理解):

start = 1
end = 3

clips = [ImageClip(os.path.join(folder,pic))
         .resize(width=w*9.3/16)
         .set_start(start)
         .set_end(end)
         .set_pos(lambda t:(max((402), (int(w-3*w*t))), "center"))
         for pic in picfiles]

第二个构造(常规循环):
start = 1
end = 3
clips = []
for pic in picfiles:
    clips.append(ImageClip(os.path.join(folder,pic))
                 .resize(width=w*9.3/16)
                 .margin(left=31, opacity=0)
                 .set_start(start)
                 .set_end(end)
                 .set_pos(lambda t:(max((402), (int(w-3*w*t))), "center")) # move from right to center
                 )

    start = start + 2
    end = end + 2

最佳答案

有很多方法可以做到。例如,您可以执行以下操作:

clips = [
ImageClip(os.path.join(folder,pic))
         .resize(width=w*9.3/16)
         .set_start(index*2+1)
         .set_end(index*2+3)
         .set_pos(lambda t:(max((402), (int(w-3*w*t))), "center"))

    for index, pic in enumerate(picfiles)
]

它使用函数枚举。这是一个显示它有效的示例。
list(enumarate(['a','b','c'])) = ((1, 'a'), (2, 'b'), (3, 'c'))

但是,您在使用这种结构时应该非常小心,因为它有时会导致难以理解的公式。对于您的代码,我认为还可以,但是当您进行更复杂的计算时,常规循环通常更清晰。

如果您的其他值不相关,您也可以使用该构造(如在您的示例中,循环索引、开始和停止之间存在简单的关系)。
[obj.setStart(start).setStop(stop) for obj, start, stop in objects, starts, stops]

您可以按照自己的方式定义开始和停止。在您的具体问题中,它应该是:
clips = [
ImageClip(os.path.join(folder,pic))
         .resize(width=w*9.3/16)
         .set_start(start)
         .set_end(stop)
         .set_pos(lambda t:(max((402), (int(w-3*w*t))), "center"))

    for start, stop, pic in
    (
        itertools.count(1, step=2),
        itertools.count(3, step=2),
        enumerate(picfiles)
    )
]

关于python - 将变量放在 python 列表理解中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37634607/

10-16 14:37