使用for循环从指定列表中选择无while循环

问题描述

我希望对for个循环执行相同的操作

menu=['salad','becon','pizza','burger','fries']

choosen_menu=''
while choosen_menu not in menu:
    print('choose something')
    choosen_menu= input()
    if choosen_menu == 'None':
        print('not hungry')
        break
else:
    print('the {} is arriving'.format(choosen_menu))

解决方法

从概念上来说,while循环在概念上适合您的用例,但如果您确实愿意,可以将其转换为等效的for循环:

from functools import partial
menu = {'salad','bacon','pizza','burger','fries'}
for chosen in iter(partial(input,'choose something\n'),'None'):
    if chosen in menu:
        print('the {} is arriving'.format(chosen))
        break
else:
    print('not hungry')

这使用了一些高级概念,例如iter()的两个参数形式(很少使用)和partial函子来部分应用函数,因此,唯一实现的就是编写代码难以阅读。否则,它或多或少与原始版本完全相同,但存在相同的可用性问题。

,

对于您的情况,我不建议使用for loop,但这将为您提供所需的信息:

from itertools import count
menu=['salad','becon','fries']

choosen_menu=''


for i in count(0):
    print('choose something')
    choosen_menu= input()
    if choosen_menu == 'None':
        print('not hungry')
        break
    elif choosen_menu not in menu:
        pass
    else:
        print('the {} is arriving'.format(choosen_menu))
        break