在 Python 中创建一个包含两个变量的循环,其中一个变量仅在每第 n 次循环后发生变化

我正在尝试编写一个程序,其中有两个列表和一个字典:


dict = {'fruit1' : 'apple', 'fruit2' :'banana', 'fruit3':'cherry' ....and so on} 

list1 = ['a','b','c','d','e'....]

list2 = ['fruit1', 'fruit2','fruit3'....]

我有一个看起来像这样的程序。[这根本不对,但它有助于代表我想要得到的结果]。


for obj1 in list1:

    for obj_2 in list2:

        print(obj1)

        print(obj_2)

        print(dict[obj_2])

我的需要是以每第n个循环改变一次obj_2但obj_1改变每个循环的方式循环它。我怎样才能做到这一点?所以我的结果看起来像(考虑第 n 个循环是第 3 个循环):


a

fruit1

apple

b

fruit1

apple

c

fruit1

apple

d

fruit2

banana

e

fruit2

banana

f

fruit2

banana

g

fruit3

cherry

.

.

.


幕布斯7119047
浏览 92回答 2
2回答

慕田峪9158850

使用计数器变量而不是嵌套循环。每次通过循环增加计数器,当它到达时n将其包装回0并将索引增加到list2.n = 3list2_index = 0counter = 0for obj1 in list1:    obj_2 = list2[list2_index]    print(obj1)    print(obj_2)    print(dict[obj_2])    counter += 1    if counter == n:        counter = 0        list2_index += 1顺便说一句,不要用作dict变量名,它是内置类型的名称。

紫衣仙女

因此,您要做的就是更改两个 for 循环的位置。#BTW it isn't adviced to use reserved keywords for variable names so dont use Dict for a variable namemyDict = {'fruit1' : 'apple', 'fruit2' :'banana', 'fruit3':'cherry'} list1 = ['a','b','c','d','e']list2 = ['fruit1', 'fruit2','fruit3']#so in this nested loop obj2 only changs after  the n loops (n being the length of list1)#which is after list1 is complete and it does that over and over #until list2 is completefor obj2 in list2:    for obj1 in list1:        print(obj1)        print(obj2)        print(myDict[obj2])如果这就是您的意思,那么这里是另一段代码。myDict = {'fruit1' : 'apple', 'fruit2' :'banana', 'fruit3':'cherry'} list1 = ['a','b','c','d','e']list2 = ['fruit1', 'fruit2','fruit3']#a variable to keep track of the nth loopnthLoop = 1 for obj2 in list2:    for obj1 in list1:        #if you print for three times which is what you wanted for your nthloop to be         #then break, which will break out of this nested loop allowing to only print 3 times and also set the         #nthLoop back to zero so that it will work nicely for the next iteration        if nthLoop > 3:            nthLoop = 0            break        print(obj1)        print(obj2)        print(myDict[obj2])        nthLoop += 1
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python