【问题标题】:Error checking whether an element is in a list检查元素是否在列表中时出错
【发布时间】:2018-09-04 21:02:47
【问题描述】:

我正在尝试检查某些元素是否在列表中,并执行数字更新,但我不断收到错误(如下)。


"if h2output[1] not in h1output == True or h2output[2] not in h1output == True:
IndexError: list index out of range"

doublewin = 0

h1output = []
h2output = []
h3output = []
v1output = []
v2output = []
v3output = []
d1output = []
d2output = []


for i in h1:
    if i not in h1output:
        h1output.append(i)
    if len(h1output) == 2:
        doublewin += 1


for i in h2:
    if i not in h2output:
        h2output.append(i)

if len(h2output) == 2:
    if h2output[1] not in h1output == True or h2output[2] not in h1output == True:
        doublewin += 1

【问题讨论】:

  • 在索引之前使用len()检查列表的长度
  • h1h2 是什么?您也不需要== True 语句,您已经在使用h2output[1] not in h1output 进行检查,这将评估为TrueFalse
  • 似乎 h1output 是一个 list,而不是 setdict,或者使用list.index(),但list.index() 将循环列表。
  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。
  • 删除 if 条件中的 True 布尔值。您在 h2output[1] 和 h2output[2] 中有硬编码索引。其中任何一个都导致了问题。请检查列表的大小。

标签: python list if-statement file-io io


【解决方案1】:

作为len(h2output)==2,它只有2个位置,在python中从零开始,因此h2output[2]越界,索引必须是01

【讨论】:

    【解决方案2】:

    您在h2output[1]h2output[2] 中有硬编码索引。其中任何一个都导致了问题。请检查列表的大小。

    删除 if 条件中的 True 布尔值,因为它是不必要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-17
      • 2017-09-24
      • 2014-07-31
      • 1970-01-01
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多