这段代码正在获取列表列表(从csv文件创建)并试图对其进行组织。我知道这看起来很混乱,我在学校已经写了几个月的代码了
无论如何,代码比较了[c]
索引的第一个索引的前7个字符(因为我必须遍历这个列表中的所有2500多个列表)。如果它们是一样的,我用这些变量做一些数学运算
除了最后一组数据外,所有这些都可以工作。由于[c+1]
when while c <len(dataList)
,我得到了“索引超出范围”或类似的结果,这就是为什么我在while语句中添加了+1
底部的if-else语句对我的代码没有影响,我不认为,但这是我解决这个问题的尝试。请解释我如何清理这个代码。谢谢
while c+1 < len(dataList):
if dataList[c][0][0:7] == dataList[c+1][0][0:7]:
totalVolume += float(dataList[c][5])
volClose += (float(dataList[c][5]) * float(dataList[c][4]))
c +=1
else:
volClose += (float(dataList[c][5]) * float(dataList[c][4]))
totalVolume += float(dataList[c][5])
avgPrice = volClose/totalVolume
averageList.append((dataList[c][0][0:7], avgPrice))
c +=1
count += 1
volClose = 0
totalVolume = 0
avgPrice = 0
if c == len(dataList):
if dataList[c][0][0:7] == dataList[c+1][0][0:7]:
totalVolume += float(dataList[c][5])
volClose += (float(dataList[c][5]) * float(dataList[c][4]))
c +=1
else:
volClose += (float(dataList[c][5]) * float(dataList[c][4]))
totalVolume += float(dataList[c][5])
avgPrice = volClose/totalVolume
averageList.append((dataList[c][0][0:7], avgPrice))
c +=1
return averageList
Python从0开始计数,因此不能转到与列表长度相等的索引。例如,像
['a', 'b', 'c']
这样的列表的长度为3,索引为0、1和2。这就是为什么会出现错误相关问题 更多 >
编程相关推荐