简体   繁体   中英

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)

This is the code i am trying to change into while loops to produce all outcomes, ie 15 outcomes, the best i can get with while loops is 3.

You can try using a while loop while also keeping an index counter variable for each list, though it is essentially just a for loop:

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

If you are willing to do a little math, you can do this in a single while loop.

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

Which prints the expected:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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