gpt4 book ai didi

python - 在Python中的for循环中跳过数组值

转载 作者:太空宇宙 更新时间:2023-11-03 14:08:01 25 4
gpt4 key购买 nike

我试图在 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':

如果他们选择该部分,我想跳到下一个组件。有什么办法可以在循环中做到这一点吗?感谢您的帮助!

最佳答案

您可以通过设置跳过标志来完成此操作,如果为 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

关于python - 在Python中的for循环中跳过数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48722574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com