8

チーム名のリストがあります。彼らがそうだとしましょう

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

プログラムでは、どのチームと一緒に仕事をしたいかをユーザーに尋ねます。チームと一致する場合、python がユーザーの入力をオートコンプリートして出力するようにします。

したがって、ユーザーが「Bla」と入力して を押すenterと、チーム Blackburn がそのスペースに自動的に出力され、コードの残りの部分で使用されます。たとえば、

あなたの選択: Bla (ユーザーは「Bla」と書いて を押しenterます)

それはどのように見えるべきか

あなたの選択: ブラックバーン (プログラムは残りの単語を終了します)

4

2 に答える 2

1

それはあなたのユースケースに依存します。プログラムがコマンドライン ベースの場合、少なくともreadlineモジュールを使用してTAB. このリンクでは、Doug Hellmann の PyMOTW 以来、よく説明されている例もいくつか提供されています。GUI 経由で試している場合は、使用している API によって異なります。その場合、いくつかの詳細を提供する必要があります。

于 2014-01-07T13:20:29.703 に答える
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 に答える