簡體   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