首页 > 解决方案 > 为什么我收到“a”不在列表中的错误?如何使这项工作打印重复元素的索引?

问题描述

import sys

j=['a','b','c','a']

l=None

leng=len(j)

try:

    l = j.index('a')

except ValueError:

    print("List does not contain value")

print("Index of first occurence is: " )

print(l)

print("Index/Indices of duplicate elements are:" )

if l<=0:
  
     while l<leng:

        l+= 1

        l=j.index('a',l,leng)

        print(l)

标签: pythonpython-3.x

解决方案


  1. 查看异常的堆栈跟踪
  2. 使用调试器,一次执行一个命令,看看哪里失败

我们可以看到

Traceback (most recent call last):
  File "C:/code/EPMD/Kodex/Applications/EPMD-Software/BaseProcess/sss.py", line 28, in <module>
    l = j.index('a', l, leng)
ValueError: 'a' is not in list

您正在寻找'a'一个不包含它的列表!

工作代码:


j = [ 'a', 'b',  'c', 'a']

l = None

leng = len(j)

try:

    l = j.index('a')

except ValueError:

    print("List does not contain value")

print("Index of first occurence is: ")

print(l)

print("Index/Indices of duplicate elements are:")

while l < leng:
    if j[l] == "a":
        print(l)
    l += 1


推荐阅读