繁体   English   中英

使用 while 循环而不是 for 循环迭代两个列表

[英]iterate over two lists using a while loop instead of a for loop

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 循环,同时为每个列表保留一个索引计数器变量,尽管它本质上只是一个 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

Output:

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

如果您愿意做一点数学运算,可以在一个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
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM