【问题标题】:How to create a loop with two variables, where one variable only changes after every nth loop?如何创建一个包含两个变量的循环,其中一个变量仅在每第 n 个循环后更改?
【发布时间】:2020-08-19 13:23:15
【问题描述】:

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

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
.
.
.

【问题讨论】:

  • “我怎样才能做到这一点?” - 请更具体地说明“this”实际上是什么=请提供完整示例输入(不是“等等”)和预期输出(我不太确定您的意思)
  • 两个for循环的交换顺序。
  • 我根据 Jan Stránský 的评论进行了一些更改。感谢您指出我的问题不够清晰。

标签: python python-3.x loops for-loop


【解决方案1】:

使用enumerate 函数和模运算符

for idx, obj1 in enumerate(list1):
    obj2 = list2[idx % n]
    # more code

【讨论】:

    【解决方案2】:

    不确定这是否是您想要的,但您可以更改两个循环的顺序。 如果你这样做:

    for obj2 in list2:
        for obj1 in list1:
            print(obj1)
            print(obj2)
            print(dict[obj2])
    

    你将让'obj1'改变每个循环,但'obj2'只有在第二个循环结束后才会改变。

    【讨论】:

      【解决方案3】:

      如果我理解您的目标,您只需切换循环语句即可。为了演示看这个简单的例子:

      n = 3
      for i in range(2):
          print(f"{i}")
          for j in range(n):
              print(f"\t{j}")
      

      编写此程序时,i 每更改一次j,就会更改一次。这将输出如下内容:

      0
          0
          1
          2
      1
          0
          1
          2
      

      【讨论】:

        【解决方案4】:
        1. dict = {key1:value1, key2:value2, ... } *使用“:”而不是“=”

        2. 这能解决你的问题吗?

           for obj_2 in list2:
              for obj1 in list1:
                 print(obj1)
                 print(obj_2)
                 print(dict[obj_2])
          

        【讨论】:

        • 感谢您的回答,打字时脑子里放了个屁。修复了字典语法,但这不是我想要的。
        猜你喜欢
        • 2018-10-13
        • 2014-08-03
        • 2011-10-22
        • 1970-01-01
        • 2021-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多