我试图从for循环中的数组中跳过一个值(或一次2个)。请参考以下代码:
loop = True
product = ['p3','p5','p7','16GB','32GB','1TB','2TB','19in','23in','Mini Tower', 'Midi Tower', '2 ports','4 ports']
while loop:
for i in product:
print('Would you like the following component: ',i,)
input()
if input == 'y':
如果他们选择那部分,我想跳到下一个部分。我有什么方法可以在循环中做到这一点?谢谢你的帮助!
答案 0 :(得分:1)
您可以通过设置跳过标志来执行此操作,如果它为True,则不执行下一次迭代:
product = ['p3','p5','p7','16GB','32GB','1TB','2TB','19in','23in','Mini Tower', 'Midi Tower', '2 ports','4 ports']
skip = False
for i in product:
if skip:
print("Skipping: " + i)
skip = False
continue
if input('Would you like the following component: ' + i) == 'y':
print("Selected: ", i)
skip = True
但是我猜你是想让这个人选择处理器,内存,屏幕等 - 这实际上是多个问题,每个问题都有多个选项。在这种情况下,我建议将其拆分为嵌套列表,并在每个选择之后停止 - 例如:
product = [['p3','p5','p7'], ['16GB','32GB','1TB','2TB'], ['19in','23in'], ['Mini Tower', 'Midi Tower'], ['2 ports','4 ports']]
for part in product:
for i in part:
if input('Would you like the following component: '+i) == 'y':
print("Selected: ", i)
break