2 回答
TA贡献1794条经验 获得超7个赞
使用计数器变量而不是嵌套循环。每次通过循环增加计数器,当它到达时n将其包装回0并将索引增加到list2.
n = 3
list2_index = 0
counter = 0
for 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变量名,它是内置类型的名称。
TA贡献1839条经验 获得超15个赞
因此,您要做的就是更改两个 for 循环的位置。
#BTW it isn't adviced to use reserved keywords for variable names so dont use Dict for a variable name
myDict = {'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 complete
for 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 loop
nthLoop = 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
添加回答
举报