Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从列表中选择的最佳方式_Python_List_Loops - Fatal编程技术网

Python 从列表中选择的最佳方式

Python 从列表中选择的最佳方式,python,list,loops,Python,List,Loops,这是一个循环,允许用户仅从列表中选择一项 types = ['Small', 'Medium','Large'] while True: print('Types: '+ types) choice = raw_input('Choose a type. ').capitalize() if choice in types: choice = choice break else: choice = raw_input

这是一个循环,允许用户仅从列表中选择一项

types = ['Small', 'Medium','Large']
while True:
    print('Types: '+ types)
    choice = raw_input('Choose a type. ').capitalize()
    if choice in types:
        choice = choice
        break
    else:
        choice = raw_input('Choose a type. ').capitalize()
我想知道这个循环是否有更小更干净的版本。一个可能的尝试版本。 这是最好的写法吗?替代品


有什么想法吗

相同,没有不必要的代码:

types = ['Small', 'Medium','Large']
print('Types: '+ types)
while True:
    choice = raw_input('Choose a type. ').capitalize()
    if choice in types:
        break

有几行是不必要的,我将向他们展示:

types = ['Small', 'Medium','Large']
while True:
    print('Types: '+ types)
    choice = raw_input('Choose a type. ').capitalize()
    if choice in types:
        #choice = choice  this is superfluos
        break
     #else: no need for else since the loop will execute again and do exactly this
     #    choice = raw_input('Choose a type. ').capitalize()
它将以如下方式结束:

types = ['Small', 'Medium','Large']
while True:
    print('Types: '+ types)
    choice = raw_input('Choose a type. ').capitalize()
    if choice in types:
        break
注意:如果您不想每次重复
类型
,只需将
打印
移出循环即可:

types = ['Small', 'Medium','Large']
print('Types: '+ types)
while True:
    ...

另外,您的代码与特定的Python版本不一致,或者您使用带括号的
raw\u input()
print()
,但不能混合使用(除非您执行一些
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu未来导入)。

什么Python版本?第二个版本中,您似乎混合了3和2(print()和raw_输入)。我习惯使用第三版的print()。明白了,这可能会产生误导:)您应该删除代码的最后两行。