Python:如何迭代嵌套在while循环中的列表?
我有以下代码:Python:如何迭代嵌套在while循环中的列表?,python,while-loop,Python,While Loop,我有以下代码: 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
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每次通过“while”循环时都会遍历列表“nthTime”
我可以使用嵌套for循环,但这当然会运行整个列表,这不是我的目标
因此,我得出结论,我需要使用嵌套的while循环;但是,我无法理解确切的语法
我希望这在将来对其他人也是一个有用的问题 类似这样:
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! ")
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
仅当用户输入正确的值时,才使用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"
每次通过while循环时,while over
nthTime
下的嵌套for循环都会在列表上迭代。您的问题是什么?我想您可能需要类似于shape=input(“为“+nthTime[iteration\u index]+”time!”选择一个形状)
?您不需要反转列表,基本上使其成为一个堆栈……无需反转。您可以简单地执行nthTime.pop(0)
,或者他可以按照正确的顺序定义字符串文本。这是一个无关紧要的问题,我倒过来尽量减少对代码的更改。我在向他演示如何使用堆栈来完成尝试。谢谢。是否可以使用while循环在列表上进行迭代?