简体   繁体   English

具有相同变量但范围不同的两个循环

[英]Two loops with same variable but different range

I want to make a program that prints n sections and x_1, x_2,..., x_n subsections for each section in LaTeX. 我想制作一个程序,为LaTeX中的每个节打印n个节和x_1,x_2,...,x_n子节。 With this I mean that I named a variable numsec, which asks me how many sections I want, easy enough. 我的意思是说我命名了一个变量numsec,它问我想要多少段,足够容易。 Then after, a variable numsubsec asks me how many subsections I want. 然后,变量numsubsec询问我要多少个小节。 Now the answer to that input ought to be like this: say I want 3 sections, my answer to the subsection has to be a 3 digit number, so that the first digit determines how many subsections should be in the first section and so on. 现在,该输入的答案应该是这样的:说我要3个部分,我对小节的答案必须是3位数字,以便第一个数字确定在第一节中应该有多少个小节,依此类推。 As an example numsec could be 3, and numsubsec could be 101. That means 1 subsec in the 1st sec, 0 subsec in 2nd sec, 1 subsec in 3rd sec. 例如,numsec可以为3,numsubsec可以为101。这意味着第一秒为1子秒,第二秒为0子秒,第三秒为1子秒。 However, I don't know how to make Python print that, exact answer. 但是,我不知道如何使Python打印出来,确切的答案。 Here is my code: 这是我的代码:

def sections(numsec, numsubsec):
    for n, i in range(1, numsec+1), range(0,len(numsubsec)):
        print("")
        print("\section{Opgave "+str(n)+"}")
        print("")
        print("\subsection{}" * int(numsubsec[i]))



def runprogram():
    numsec = int(input("How many sections? "))
    numsubsec = input("How many subsections? ")
    sections(numsec,numsubsec)

runprogram()

EDIT: I solved the issue by using to for loops simultaneously with two variables as such: 编辑:我通过同时使用两个变量的for循环解决了这个问题:

def sections(numsec, numsubsec):
    numbers = []
    numbers.extend(numsubsec) #Splitting the string numsubsec in to a list of its digits
    print("")
    print("Preamble")
    print("")
    for n,i in zip(range(1, numsec+1),range(0,numsec)): #zip the ranges
        print("")
        print("\section{Opgave "+str(n)+"}")
        print("")
        for x in range(int(numsubsec[i])):
            print("\subsection{}")
            print("")

This can be solved by using two for loops simultaneously, and zipping the ranges as such: 可以通过同时使用两个for循环并压缩范围来解决此问题:

def sections(numsec, numsubsec):
    numbers = []
    numbers.extend(numsubsec) #Splitting the string numsubsec in to a list of its digits
    print("")
    print("Preamble")
    print("")
    for n,i in zip(range(1, numsec+1),range(0,numsec)): #zip the ranges
        print("")
        print("\section{Opgave "+str(n)+"}")
        print("")
        for x in range(int(numsubsec[i])):
            print("\subsection{}")
            print("")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM