我有一份团队名单。假设他们是
teamnames=["Blackpool","Blackburn","Arsenal"]
在程序中,我询问用户他想与哪个团队一起做事。我希望 python 在与团队匹配时自动完成用户的输入并打印它。
因此,如果用户写下“Bla”并按 enter,布莱克本队应该会自动打印在该空间中并在其余代码中使用。例如;
您的选择:Bla(用户输入“Bla”并按enter)
它应该是什么样子
您的选择:布莱克本(该程序完成了单词的其余部分)
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]
这取决于您的用例。如果您的程序是基于命令行的,您至少可以通过使用 readline 模块并按 TAB 来完成此操作。此链接还提供了一些解释良好的示例,因为它是 Doug Hellmanns PyMOTW。如果您通过 GUI 进行尝试,则取决于您正在使用的 API。在这种情况下,您需要提供更多详细信息。