无法通过从列表列表中随机选择的索引访问列表

时间:2016-07-14 16:01:03

标签: python list random

我正在进行python学习练习,需要从控制台创建一个文本游戏。我想创建一个琐事游戏。 (是的,这是哈利波特的琐事 - 请不要判断)要制作问题池,我已经制作了问题,答案选项和答案的文本文件。为了在随机选择问题时保留正确的选项和答案,我使用的是列表清单。但是当我从列表列表中拉出其中一个列表并将其分配给变量时,通过索引访问它会拉动索引处的字符,而不是列表项。

以下是文本文件中的示例数据,名为questions.txt:

['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]

每个列表中的第一项是问题,第二项,第三项和第四项是答案选项,最后一个整数是正确答案的编号。我将它导入我的python文件并使用分割线,以便文本文件中的每一行成为列表中的项目,从而列出一个列表。

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?

我确信这里有一些我不想要的东西......

2 个答案:

答案 0 :(得分:1)

Python正在将您的文件行读取为字符串。字符串看起来像Python列表,但它们不是。为了将问题存储在文本文件中,您应该使用像json这样的数据格式。请参阅此问题以供参考:Parsing values from a JSON file using Python?

答案 1 :(得分:0)

我还建议您阅读repr()eval()内置函数,以防您认为json模块过大。在最简单的形式中,eval()允许您将字符串计算为正确的数据结构,例如元组或列表(如您的情况)。

相关问题