2016-07-14 3 views
0

私は、コンソールから実行されるテキストゲームを作成する必要があるpython学習の練習に取り組んでいます。私はトリビアゲームを作りたい。 (はい、それはハリー・ポッターのトリビアです - 判断しないでください)質問プールを作るために、質問、回答オプション、および回答のテキストファイルを作成しました。無作為に選んだときの質問と正しいオプションと答えを保持するために、私はリストのリストを使用しています。しかし、リストの1つをリストの外に出して変数に代入すると、インデックスでアクセスするとリストの項目ではなくインデックスの文字が取り出されます。各リストの最初の項目は疑問、第二、第三であり、第4解答選択肢ですリストからランダムに選択されたインデックスでリストにアクセスすることはできません

['What was the famous Albus Dumbledore\'s full name?','Albus Merlin Baowulf Roderick Dumbledore','Albus Cato Eleret Scholasticus Dumbledore','Albus Percival Wulfric Brian Dumbledore',3] 
['What fruit must you tickle to get into the Hogwarts kitchen?','Pear','Apple','Quince',1] 
['What is the name of the French wizarding school?','Acadamie de Magique','Beauxbatons','Fontainebleu',2] 
['What is the name of Mr. Filch\'s cat?','Mr. Pinky Paws','Crookshanks','Mrs. Norris',3] 

、および:ここでは

はquestions.txtという名前のテキストファイル内のデータ例であり、最終的な整数は正解の数です。私はこれを私のpythonファイルにインポートし、splitlinesを使って、テキストファイルの各行がリスト内の項目、つまりリストのリストになるようにします。

with open('questions.txt', 'r') as infile: 
    questions = infile.read() 

my_questions = questions.splitlines() 

この時点で、my_questionsのインデックスをインデックスで印刷してテストしました。

print my_questions[0] 

は、だから私はランダムにリストからリストのいずれかを選択して、新しい変数に代入する次のステップを行った

['What was the famous Albus Dumbledore\'s full name?','Albus Merlin Baowulf Roderick Dumbledore','Albus Cato Eleret Scholasticus Dumbledore','Albus Percival Wulfric Brian Dumbledore',3] 

になりました。私は関数を作成しました(ファイルの先頭にランダムにインポートしたことを確認しました):

def question(): 
     quest = random.choice(my_questions) 

     print quest[0] 

私。最初の文字であり、最初の文字ではありません。

私は質問と回答のリストをハードコードし、同じテストを試みました。コード:

def question(): 
     quest = random.choice(my_questions) 
     quest1 = ['What is the name of Mr. Filch\'s cat?','Mr. Pinky Paws','Crookshanks','Mrs. Norris',3] 
     print quest 
     print quest[0] 
     print quest1 
     print quest1[0] 

と結果は以下のとおりであった:

PS C:\Users\Katrina\temp> python hogwarts.py 
['What fruit must you tickle to get into the Hogwarts kitchen?','Pear','Apple','Quince',1] 
[ 
["What is the name of Mr. Filch's cat?", 'Mr. Pinky Paws', 'Crookshanks', 'Mrs. Norris', 3] 
What is the name of Mr. Filch's cat? 

私は私がここで行方不明です何かがあると確信している...

答えて

1

は、Pythonは文字列として、あなたのファイルの行を読んでいます。文字列はPythonリストのように見えますが、そうではありません。質問をテキストファイルに保存するには、jsonのようなデータ形式を使用する必要があります。 Parsing values from a JSON file using Python?

0

jsonモジュールを過度の機能とみなす場合は、repr()eval()の組み込み関数を読むことをお勧めします。最も単純な形式では、eval()を使用すると、文字列をタプルやリストなどの適切なデータ構造に評価することができます。

関連する問題