python - 为什么我收到“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)
解决方案
- 查看异常的堆栈跟踪
- 使用调试器,一次执行一个命令,看看哪里失败
我们可以看到
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
推荐阅读
- google-bigquery - BigQuery 中的不同总结果
- typescript - 在 Typescript 中使用和测试保镖模式
- php - 如何在 Magento 的元描述中附加 sku。?
- .net - 如何从 .NET Blazor 中的另一个 ChildComponent 访问 ChildComponent 中的函数
- django - 使用 SimpleJWT 登录时的 AnonymousUser
- c++ - BMP文件的8位读/写
- python - 如何查看django对象查询速度
- javascript - JavaScript 中的圆周运动未按预期工作
- json - Scala,Circe,Http4s - 有什么方法可以在 Circe 中编码 Throwable?
- angular - 如何为 PWA 新闻应用执行后台更新