8

我有一个团队名称列表。假设他们是

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

在程序中,我问用户他想和哪个团队一起做事。如果它与团队匹配,我希望 python 自动完成用户的输入并打印它。

因此,如果用户写“Bla”并按下enter,则应该在该空间中自动打印 Blackburn 团队并在其余代码中使用。例如,例如;

您的选择:Bla(用户写“Bla”并按enter

它应该是什么样子

你的选择:布莱克本(程序完成了剩下的单词)

4

2 回答 2

1
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]
于 2014-01-07T13:16:55.800 回答
1

这取决于您的用例。如果您的程序是基于命令行的,您至少可以使用readline模块并按TAB. 自 Doug Hellmanns PyMOTW 以来,此链接还提供了一些很好解释的示例。如果您通过 GUI 进行尝试,则取决于您使用的 API。在这种情况下,您需要提供更多详细信息。

于 2014-01-07T13:20:29.703 回答