2016-01-02 118 views
-1

我有以下代碼:Python:如何遍歷嵌套在while循環中的列表?

shape = input("Please enter your choice of shape? ")  

nthTime = ["second","third","fourth","fifth","sixth"] 

while shape.lower() not in ["octagon","heptagon","hexagon"] : 
    print("Please select a shape from the list!") 
    shape = input("Pick a shape, for the " + nthTime + " time! ") 

我如何才能實現的結果,即Python會每經過一次迭代名單「nthTime」,通過'while循環?

我可以使用嵌套for循環,但當然這將運行整個列表,這不是我的目標。

因此,我得出結論,我需要使用嵌套的while循環;但我無法弄清楚確切的語法。

我希望這對未來的其他人也是一個有用的問題。

+0

嵌套for循環,而下通過'nthTime' **將**每次通過while循環*時遍歷整個列表。你有什麼問題? –

+0

我想你可能想要像'shape = input(「選擇一個形狀,爲」+ nthTime [iteration_index] +「time!」)'? – Netwave

回答

1

事情是這樣的:

shape = input("Please enter your choice of shape? ")  

nthTime = ["second","third","fourth","fifth","sixth"] 
undesired_shapes = ["octagon","heptagon","hexagon"] 

indx = 0 

while shape.lower() not in undesired_shapes: 
    print("Please select a shape from the list!") 
    shape = input("Pick a shape, for the " + nthTime[indx] + " time! ") 
    indx += 1 
    if indx >= len(nthTime): 
     print 'Giving up !!' 
     break 
0
nthTime.reverse() 

while shape.lower() not in ["octagon","heptagon","hexagon"] and nthTime: 
    print("Please select a shape from the list!") 
    shape = input("Pick a shape, for the " + nthTime.pop() + " time! ") 
+0

您不需要扭轉列表並且基本上使它成爲堆棧... –

+0

不需要反轉。你可以簡單地做'nthTime.pop(0)' –

+0

或者他可以只按照正確的順序定義字符串文字。這是一個微不足道的問題,爲了儘量減少對代碼的更改,我倒過來了。我向他展示瞭如何使用堆棧來消除這些嘗試。 – donopj2

2

使用一個for循環,打破循環,只有當用戶輸入正確的值

for iteration in nthTime: 
    if shape.lower() not in ["octagon","heptagon","hexagon"]: 
     print("Please select a shape from the list!") 
     shape = input("Pick a shape, for the " + iteration + " time! ") 
    else: break 
else: print "You have wasted all your chances, try again later" 
+0

謝謝。是否有可能使用while循環遍歷列表? –