2 回答

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
使用計(jì)數(shù)器變量而不是嵌套循環(huán)。每次通過(guò)循環(huán)增加計(jì)數(shù)器,當(dāng)它到達(dá)時(shí)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
順便說(shuō)一句,不要用作dict變量名,它是內(nèi)置類型的名稱。

TA貢獻(xiàn)1839條經(jīng)驗(yàn) 獲得超15個(gè)贊
因此,您要做的就是更改兩個(gè) for 循環(huán)的位置。
#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
添加回答
舉報(bào)