如何从这段代码创建一个循环?

时间:2016-09-14 08:17:23

标签: python logic

我有一个python例程,它将PDF页面放在小册子传播顺序中。我试图改进代码:有一点我在两次做同样的事情。当我写出迭代时,它可以正常工作,但是当我尝试使用更多循环使其更通用时,它并没有。该代码将两个PDF页面放在一个更大的PDF页面上。

# For each side of the sheet, we must create a PDF page,
# take two source pages and place them differently, then close the page.
# If the source page number is 0, then move on without drawing.
    Sides = len(imposedOrder) / pagesPerSide
    count = 0
    for n in range(Sides):
        Quartz.CGContextBeginPage(writeContext, sheetSize)
        if imposedOrder[count]:
            page = Quartz.CGPDFDocumentGetPage(source, imposedOrder[count])
            Quartz.CGContextSaveGState(writeContext)
            Quartz.CGContextConcatCTM(writeContext, Quartz.CGPDFPageGetDrawingTransform(page, Quartz.kCGPDFMediaBox, leftPage, 0, True))
            Quartz.CGContextDrawPDFPage(writeContext, page)
            Quartz.CGContextRestoreGState(writeContext)
        count += 1  

        if imposedOrder[count]:
            page = Quartz.CGPDFDocumentGetPage(source, imposedOrder[count])
            Quartz.CGContextSaveGState(writeContext)
            Quartz.CGContextConcatCTM(writeContext, Quartz.CGPDFPageGetDrawingTransform(page, Quartz.kCGPDFMediaBox, rightPage, 0, True))
            Quartz.CGContextDrawPDFPage(writeContext, page)
            Quartz.CGContextRestoreGState(writeContext)
        count += 1  
        Quartz.CGContextEndPage(writeContext)

所以每次唯一不同的是我们是使用leftPage还是rightPage。

以下是DOESN&T的工作版本:

count = 0
for n in range(Sides):
    Quartz.CGContextBeginPage(writeContext, sheetSize)
    for nn in range (1, pagesPerSide+1):
        if nn%2 == 1:
            position = leftPage
        else:
            position = rightPage
        if imposedOrder[count]:
            page = Quartz.CGPDFDocumentGetPage(source, imposedOrder[count])
            Quartz.CGContextSaveGState(writeContext)
            Quartz.CGContextConcatCTM(writeContext, Quartz.CGPDFPageGetDrawingTransform(page, Quartz.kCGPDFMediaBox, position, 0, True))
            Quartz.CGContextDrawPDFPage(writeContext, page)
            Quartz.CGContextRestoreGState(writeContext)
        count += 1
    Quartz.CGContextEndPage(writeContext)

0 个答案:

没有答案