如何解决在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])
我需要以obj_2
每第n个循环更改一次,但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
.
.
.
解决方法
因此要达到目标,您要做的就是更改两个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','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
作为变量名,它是内置类型的名称。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。