簡體   English   中英

從列表中選擇的最佳方法

[英]Best way to select from a list

這是一個循環,允許用戶從列表中僅選擇一個項目。

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只需將print移出循環即可:

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

另外,您的代碼與特定的Python版本不一致,您可以在帶有括號的情況下使用raw_input()print() ,但不能混合使用(除非您進行__future__導入)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM