gpt4 book ai didi

python - 索引错误: list index out of range but I "know" it is

转载 作者:行者123 更新时间:2023-12-01 04:53:32 27 4
gpt4 key购买 nike

我想知道为什么可能会发生以下情况:

我有一个 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

到目前为止:

  1. 如果我写每个 all_hits[i][1]文件长度 >=3 个字符,我达到大约 18,000 个条目,但如果我打印 len(all_hits)答案是 39,000 个元素。
  2. 我可以打印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 中的每个列表至少有 2 个条目长。

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com