作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想知道为什么可能会发生以下情况:
我有一个 list :
all_hits = list1 + list2
length_hits = len(all_hits)
i = 0
while i < int(length_hits) - 1:
if len((all_hits[i])[1]) >=3:
Do x
else:
Do y
这给了我一个错误:
File "file.py", line z, in Function:
if len((all_hits[i])[1]) >= 3:
IndexError: list index out of range
到目前为止:
all_hits[i][1]
文件长度 >=3 个字符,我达到大约 18,000 个条目,但如果我打印 len(all_hits)
答案是 39,000 个元素。all_hits[-1]
条目与书面列表中的最终条目不符。据我所知,我不会更改原始列表。
为什么?!我已经解决这个问题 2 天了,这让我发疯。
编辑:3. 我已经打印了最终条目以及之后/之前的一些内容,以确保它们具有正确数量的元素,并且那里的一切看起来都正常。
编辑并感谢您:
谢谢大家。当然,你是对的。我的一个条目突然只有一个列表对象。我不知道如何或为什么,但这完全是另一回事!
感谢您的帮助!
最佳答案
在这一行中 if len((all_hits[i])[1]) >= 3:
你应该知道双重取消引用所假设的内容 [i][1]
:
all_hits
是列表的列表。例如[[1,2],[4,5],[7,8],[9]]
all_hits[0]
指的是 all_hits
中的第一个列表/条目 - 在我的示例中为 [1,2]
。
因此 all_hits[0][1]
引用 [1,2]
示例列表中的第二个元素,即 2
。
现在您可以想象,当您到达 all_hits
中的第四个条目(即我的示例中的 [9]
)时。
all_hits[3]
= [9] 但 all_hits[3][1]
超出范围,因为您只有一个条目,即 all_hits[ 3][0]
因此请确保每个嵌套列表的长度至少为 2 个条目。如果您知道它们是那么您就不应该遇到问题。而是尝试这个:
all_hits = list1 + list2
i = 0
while i <= len(all_hits) - 1:
if len(all_hits[i][1]) >=3:
Do x
else:
Do y
i += 1
关于python - 索引错误: list index out of range but I "know" it is,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27940697/
我是一名优秀的程序员,十分优秀!