【问题标题】:Value Error when trying to match index in two lists尝试匹配两个列表中的索引时出现值错误
【发布时间】:2013-10-28 22:32:26
【问题描述】:

我正在尝试用 Python 编写一些简单的抽认卡(仍在学习中!)。

我可以读入一个文本文件,分成两个列表(关键字和定义),找到一个随机关键字(chosenKeyword)并从关键字列表中返回关键字及其索引值,但是当我尝试使用它时索引值(在第二个列表中与我在同一时间逐行读取它们时完全相同)以匹配定义列表我不断收到ValueError 告诉我该项目不在列表中(当我手动检查时)。问题出在我的 possibleAnswers 函数中,但我无法弄清楚它是什么 - 任何帮助都会很棒。

# declare an empty list for answers
answers = []

if keyword.index(chosenKey) == define.index(chosenKey):
    answers.append()
else:
    pass


# find the matching definition for the keyword and add to the answer list

wrongAnswers = random.sample(define,2)
while define.index(chosenKey) != wrongAnswers:
    answers.append(wrongAnswers)
    print(answers)

【问题讨论】:

  • 请发SSCCE
  • 我不太确定你在做什么,但 answers.append() 看起来不太好。
  • 这部分也很奇怪while define.index(chosenKey) != wrongAnswers

标签: python list indexing


【解决方案1】:

list.index() 返回列表中给定的索引:

>>> ['spam', 'ham', 'eggs'].index('ham')
1

但在列表中未找到该项目时引发ValueError

>>> ['spam', 'ham', 'eggs'].index('monty')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'monty' is not in list

如果您有索引,只需在列表中使用索引:

>>> ['spam', 'ham', 'eggs'][1]
'ham'

如果您想配对两个列表的元素,请改用zip() function

for kw, definition in zip(keyword, define):
    if kw == definition:
        # the values match at the same index.

【讨论】:

  • 感谢您的帮助,我了解 Value Error 的含义以及它与索引的关系。我不知道为什么如果我从列表 1 中有一个索引值(我检查的是一个 int),我不能只从列表 2 中获取该索引位置的实际值。我已经尝试了您的建议,但一直收到与逗号“if kw,definition in zip(keyword,define):”相关的错误,并且无法正常工作。
  • @user2127168:啊,那是因为那里有一个错字;我的意思是这是一个for 循环。我很抱歉。
【解决方案2】:

我认为您在显示的代码中存在一些问题

这是第一个:

if keywords.index(chosenKey) == definitions.index(chosenKey):

据我了解,您想在答案列表中添加正确答案。

我会这样做:

if chosenKey in keywords:
    answers.append(definitions[keywords.index(chosenKey)])
else:
    pass

第二部分似乎有人试图获得两个随机选项,其中一个应该是正确答案

wrongAnswers = random.sample(define,2)
while definitions[keywords.index(chosenKey)] not in wrongAnswers:        
    wrongAnswers = random.sample(define,2)
answers = wrongAnswers
print(answers)

【讨论】:

  • 感谢您的帮助,这个解决方案对我来说效果最好,尽管我仍然尝试让它按我想要的方式工作。除非我改变它,否则我无法让建议的 if 语句起作用。我发现 Online Python Tutor 对于实际查看我的列表和变量中发生的事情非常有用 - 再次感谢。
猜你喜欢
  • 2020-09-29
  • 1970-01-01
  • 2017-07-18
  • 2022-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多