【问题标题】:iterate over two lists using a while loop instead of a for loop使用 while 循环而不是 for 循环遍历两个列表
【发布时间】:2021-08-14 02:11:38
【问题描述】:
colours = ["red", "green", "blue"]
clothes = ["shirt", "dress", "pants", "jacket", "hat"]


for colour_item in colours:
    for clothes_item in clothes:
        print("I am wearing a ",colour_item," ",clothes_item)

这是我试图更改为 while 循环以产生所有结果的代码,即 15 个结果,我可以使用 while 循环获得的最佳结果是 3。

【问题讨论】:

  • 为什么要为此使用 while 循环?
  • 包括你的while循环代码。

标签: python for-loop while-loop


【解决方案1】:

您可以尝试使用 while 循环,同时为每个列表保留一个索引计数器变量,尽管它本质上只是一个 for 循环:

colours = ["red", "green", "blue"]
clothes = ["shirt", "dress", "pants", "jacket", "hat"]

colorIndex = 0
while(colorIndex < len(colours)):
  clothesIndex = 0
  while(clothesIndex < len(clothes)):
    print("I am wearing a",colours[colorIndex],clothes[clothesIndex])
    clothesIndex += 1
  colorIndex += 1

输出:

I am wearing a red shirt
I am wearing a red dress
I am wearing a red pants
I am wearing a red jacket
I am wearing a red hat
I am wearing a green shirt
I am wearing a green dress
I am wearing a green pants
I am wearing a green jacket
I am wearing a green hat
I am wearing a blue shirt
I am wearing a blue dress
I am wearing a blue pants
I am wearing a blue jacket
I am wearing a blue hat

【讨论】:

    【解决方案2】:

    如果您愿意做一些数学运算,可以在单个 while 循环中完成。

    colours = ["red", "green", "blue"]
    clothes = ["shirt", "dress", "pants", "jacket", "hat"]
    
    n = 0
    l = len(clothes)
    
    while n < len(colours) * len(clothes):
        print(f"I am wearing a {colours[n // l]}  {clothes[n % l]}")
        n += 1
    

    打印预期的:

    I am wearing a red  shirt
    I am wearing a red  dress
    I am wearing a red  pants
    I am wearing a red  jacket
    I am wearing a red  hat
    I am wearing a green  shirt
    I am wearing a green  dress
    I am wearing a green  pants
    I am wearing a green  jacket
    I am wearing a green  hat
    I am wearing a blue  shirt
    I am wearing a blue  dress
    I am wearing a blue  pants
    I am wearing a blue  jacket
    I am wearing a blue  hat
    

    【讨论】:

    • 我不认为这更有效,它仍然是 O(n^2)
    • @AnikethMalyala 考虑到 OP 想要打印 m * n 项目 O(n * m) 似乎不可能被击败。这在循环中表达得很清楚len(colours) * len(clothes)
    • O(m*n),我的错。我以为你是在暗示你的单数 while 循环比嵌套循环更有效,我的错!
    • @AnikethMalyala 我可以看到它看起来如何。但是不,只是使代码更短(但可能不是更清晰)。就个人而言,我认为for 循环或itertools.product 是正确的方法。
    • Fr,在这种情况下使用 for each loop 接缝会更好
    【解决方案3】:
    colours = ["red", "green", "blue"]
    clothes = ["shirt", "dress", "pants", "jacket", "hat"]
    
    i=0
    while i<len(colours):
        j=0
        colour_item = colours[i]
        while j<len(clothes):
            clothes_item = clothes[j]
            print("I am wearing a ",colour_item," ",clothes_item)
            j+=1
        i+=1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      相关资源
      最近更新 更多