在Python中创建一个包含两个变量的循环,其中一个变量仅在每个第n个循环后更改,而另一个变量在每个循环中更改
我正在尝试编写一个程序,其中有两个列表和一个字典:在Python中创建一个包含两个变量的循环,其中一个变量仅在每个第n个循环后更改,而另一个变量在每个循环中更改,python,python-3.x,for-loop,Python,Python 3.x,For Loop,我正在尝试编写一个程序,其中有两个列表和一个字典: 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
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])
我需要的是以一种循环方式来循环,即obj_2
每第n个循环改变一次,而obj_1
每一个循环改变一次。我怎样才能做到这一点?
因此,我的结果如下(考虑到第n个循环是第3个循环):
所以你要做的就是改变两个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])
编辑
我可能误解了@Barmar所说的第三个循环的意思。如果这就是你的意思,这里还有另一段代码
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
使用计数器变量而不是嵌套循环。每次通过循环时递增计数器,当计数器达到
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
作为变量名,它是内置类型的名称。这会打印1苹果的5次,而不是3次。谢谢你的回答!但是,我试图将“水果1”的打印次数限制为3次,而不是基于列表1的长度,如果我们假设列表1是26个字符long@user14131697现在呢?新的解决方案能回答你的问题吗
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