0

さて、以下は私の問題です:

このプログラムはファイルから読み込み、rstrip('\n') を使用せずにリストを作成しますが、これは私が意図的に行ったものです。そこから、リストを印刷し、並べ替え、再度印刷し、並べ替えられた新しいリストをテキスト ファイルに保存し、リストで値を検索できるようにします。

私が抱えている問題はこれです:

名前を検索すると、どのように入力しても、リストにないことがわかります。

コードは、変数のテスト方法を変更するまで機能しました。検索機能は次のとおりです。

def searchNames(nameList):
    another = 'y'
    while another.lower() == 'y':
        search = input("What name are you looking for? (Use 'Lastname, Firstname', including comma: ")

        if search in nameList:
            print("The name was found at index", nameList.index(search), "in the list.")
            another = input("Check another name? Y for yes, anything else for no: ")
        else:
            print("The name was not found in the list.")
            another = input("Check another name? Y for yes, anything else for no: ")

完全なコードについては、http://pastebin.com/PMskBtzJ

テキストファイルの内容:http: //pastebin.com/dAhmnXfZ

アイデア?検索変数に ( + '\n') を追加しようとしたことに注意する必要があるように感じます

4

3 に答える 3

3

改行を明示的に削除しなかったとあなたは言います。

したがって、 yournameListは のような文字列のリストです['van Rossum, Guido\n', 'Python, Monty\n']

しかし、 yoursearchは によって返される文字列であり、改行inputありません。したがって、リスト内のどの文字列とも一致しない可能性があります。

これを修正するにはいくつかの方法があります。

まず、もちろん、リストから改行を取り除くことができます。

または、検索中にその場で削除することもできます。

if search in (name.rstrip() for name in nameList):

searchまたは、それらを文字列に追加することもできます。

if search+'\n' in nameList:

多くの検索を行っている場合は、削除を 1 回だけ行い、削除された名前のリストを保持します。


補足として、リストを検索して名前がリストにあるかどうかを確認し、再度検索してインデックスを見つけるのは少しばかげています。一度検索するだけです:

try:
    i = nameList.index(search)
except ValueError:
    print("The name was not found in the list.")
else:
    print("The name was found at index", i, "in the list.")
another = input("Check another name? Y for yes, anything else for no: ")
于 2013-11-12T21:44:29.100 に答える