gpt4 book ai didi

python - 循环中的超出范围问题

转载 作者:行者123 更新时间:2023-11-28 17:30:59 25 4
gpt4 key购买 nike

我尝试制作一个允许循环遍历列表的脚本 (tmpList = openFiles(cop_node))。此列表包含 5 个其他 206 个组件的子列表。子列表的最后 200 个组件是字符串编号(每个组件的一行 200 个字符串编号,用空格字符分隔)。

我需要遍历主列表并创建一个包含 5 个组件的新列表,每个新组件包含 200*200 个浮点值。

我的实际代码是尝试将第二个循环添加到与一个子列表等效的旧代码中。但是 python 返回错误 "Index out of range"

def valuesFiles(cop_node):
tmpList = openFiles(cop_node)
valueList = []
valueListStr = []*len(tmpList)
for j in range (len(tmpList)):
tmpList = openFiles(cop_node)[j][6:]
tmpList.reverse()
for i in range (len(tmpList)):
splitList = tmpList[i].split(' ')
valueListStr[j].extend(splitList)
#valueList.append(float(valueListStr[j][i]))
return(valueList)

最佳答案

valueListStr = []*len(tmpList) 并没有按照您的想法行事,如果您想要一个列表列表,请使用范围为 list comp 的列表:

valueListStr = [[] for _ in range(len(tmpList))]

这将创建一个列表列表:

In [9]: valueListStr = [] * i

In [10]: valueListStr
Out[10]: []

In [11]: valueListStr = [[] for _ in range(i)]

In [12]: valueListStr
Out[12]: [[], [], [], []]

所以你得到错误的原因是因为valueListStr[j].extend(splitList),你不能索引一个空列表。

你实际上似乎并没有在任何地方返回列表所以我假设你真的想要返回它,你也可以根据需要在循环内创建列表,你也可以循环 tmpListopenFiles(cop_node):

def valuesFiles(cop_node):
valueListStr = []
for j in openFiles(cop_node):
tmpList = j[6:]
tmpList.reverse()
tmp = []
for s in tmpList:
tmp.extend(s.split(' '))
valueListStr.append(tmp)
return valueListStr

使用itertools.chain可以变成:

from itertools import chain
def values_files(cop_node):
return [list(chain(*(s.split(' ') for s in reversed(sub[6:]))))
for sub in openFiles(cop_node)]

关于python - 循环中的超出范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34406393/

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