检查元素是否在lis中时出错

2024-06-16 09:41:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图检查某些元素是否在一个列表中,并执行数字更新,但我不断得到一个错误(如下)。你知道吗


"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

Tags: orintrue元素列表forlenif
2条回答

h2output[1]h2output[2]中有硬编码索引。他们中的任何一个都是问题的根源。请检查一下名单的大小。你知道吗

去掉if条件中的真布尔,因为它是不必要的。你知道吗

由于len(h2output)==2,它只有两个位置,在python中,这两个位置从零开始,因此h2output[2]超出界限,索引必须是01

相关问题 更多 >