2014-01-07 90 views
1

我有一個團隊名單。假設他們是Python自動完成用戶輸入

teamnames=["Blackpool","Blackburn","Arsenal"] 

在程序中,我問用戶哪個團隊,他想做的東西。我希望python自動完成用戶的輸入,如果它匹配一個團隊並打印它。

因此,如果用戶寫入「Bla」並按輸入,則團隊Blackburn應自動打印在該空間中並用於其餘代碼。舉例來說,

您的選擇:布拉(用戶寫道:「布拉」並按下進入

它應該是什麼樣子

您的選擇:布萊克本(程序完成單詞的其餘部分)

+0

那麼你到現在爲止嘗試過什麼,你也應該包括它。讓我們看看你的努力,直到現在。你在哪裏堅持你的代碼。 – 2014-01-07 14:02:08

+0

爲什麼這個問題脫離主題?它似乎明確要求如何在Python中給出一個可能的輸入列表來實現「輸入」 - 完成(如tab-completion)。 – travelingbones

回答

2
teamnames=["Blackpool","Blackburn","Arsenal"] 

user_input = raw_input("Your choice: ") 

# You have to handle the case where 2 or more teams starts with the same string. 
# For example the user input is 'B'. So you have to select between "Blackpool" and 
# "Blackburn" 
filtered_teams = filter(lambda x: x.startswith(user_input), teamnames) 

if len(filtered_teams) > 1: 
    # Deal with more that one team. 
    print('There are more than one team starting with "{0}"'.format(user_input)) 
    print('Select the team from choices: ') 
    for index, name in enumerate(filtered_teams): 
     print("{0}: {1}".format(index, name)) 

    index = input("Enter choice number: ") 
    # You might want to handle IndexError exception here. 
    print('Selected team: {0}'.format(filtered_teams[index])) 

else: 
    # Only one team found, so print that team. 
    print filtered_teams[0] 
0

這取決於你的用例。如果您的程序是基於命令行的,那麼至少可以通過使用readline模塊並按TAB來完成。自從Doug Hellmanns PyMOTW以來,該鏈接還提供了一些很好解釋的例子。如果您通過GUI嘗試,則取決於您使用的API。在這種情況下,您需要提供更多的細節。