将变量放在python列表中理解

时间:2016-06-04 20:15:53

标签: python

以下两个循环结构基本相同。我无法弄清楚如何在第一个语法中插入两个变量start = start+2end = end+2。谢谢

FIRST CONSTRUCT(列表理解):

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]

SECOND CONSTRUCT(常规循环):

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

1 个答案:

答案 0 :(得分:3)

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

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)
    )
]