python - 如何解决 Python:IndexError:列表索引超出范围?
问题描述
我正在尝试计算“args”列表中“-1”的出现次数。'-1' 出现在很多地方,所以当它连续出现不止一次时,我希望算上它。
我收到“列表索引超出范围”错误,但这是错误的。我正在尝试访问第 16 个元素,“args”的长度为 19。在第 5 行和第 6 行,我分别打印索引和列表的元素,这些行执行没有错误。
为什么我会收到错误消息?而且第10行的print语句没有打印,是什么原因呢?
args=[-3, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1, -1, -1, -3, -1, -2, -1, -1, -1]
i=0
while i<= len(args)-1:
count=0
print(i)
print(args[i])
while args[i]==-1:
count+=1
i+=1
print("count="+str(count)+"-"+str(i))
i+=1
$python main.py
0
-3
count=0-0
1
-1
count=4-5
6
-1
count=2-8
9
-1
count=4-13
14
-1
count=1-15
16
-1
Traceback (most recent call last):
File "main.py", line 8, in <module>
while args[i]==-1:
IndexError: list index out of range
解决方案
IndexError 是因为您的内部while
循环。您正在递增i
而没有检查它是否超过列表长度并尝试访问它。
还有另一种方法可以解决这个问题。
您可以跟踪先前访问的元素,检查它是否为 -1 并检查先前元素和当前元素是否相同,然后才增加计数器count
args=[-3, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1, -1, -1, -3, -1, -2, -1, -1, -1]
prev = args[0]
count = 0
i = 1
while i < len(args):
if args[i] == -1 and args[i] == prev:
count += 1
else:
if count > 1:
print(count)
count = 1
prev = args[i]
if i == len(args) - 1 and count > 1:
print(count)
i+=1
这将打印-1
列表中连续出现的 s 的计数。
推荐阅读
- javascript - TypeError:无法读取null的属性'awaitMessages'当它与其他相同时
- r - 如何在结束 Shiny 应用程序时运行 Shiny 应用程序?
- flutter - Flutter - 在一个请求中映射两个列表
- docker - 无法 ssh 进入 docker 容器 centOS 服务器
- leaflet - 使用leaflet.FreeDraw 和leaflet.path.drag
- c# - ASP.Net Core 身份和配置文件数据
- javascript - 带有“\ w”的Javascript单词边界正则表达式用于带有双字节字符的单词
- python - 在 python 上加载一个 gpx 文件
- ios - Alamofire EmptyResponseCodes 不起作用
- node.js - Loopback 4:如何编辑由 `Entity` 道具上的`@property` 装饰器设置的元数据?