首页 > 解决方案 > Python(迭代问题)与练习

问题描述

编码 :

import pandas as pd 
import numpy as np
import csv
data = pd.read_csv("/content/NYC_temperature.csv", header=None,names = ['temperatures'])

np.cumsum(data['temperatures'])
printcounter = 0
list_30 = [15.22]#first temperature , i could have also added it by doing : list_30.append(i)[0] since it's every 30 values but doesn't append the first one :)
list_2 = [] #this is for the values of the subtraction (for the second iteration)
for i in data['temperatures']: 
    if (printcounter == 30):
        list_30.append(i)
        printcounter = 0
    printcounter += 1
**for x in list_30:
  substract = list_30[x] - list_30[x+1]**
  list_2.append(substraction)
print(max(list_2))

大家好 !我真的对黑色部分有问题。

**for x in list_30:
  substract = list_30[x] - list_30[x+1]**

我正在尝试迭代元素并使用下一个元素 (x+1) 提取元素 x,但会弹出以下错误TypeError: 'float' object is not iterable。我也尝试过使用x而不是迭代,list_30[x]但是当我使用时,我遇到next(x)了另一个错误。

标签: python

解决方案


for x in list_30:将在 list_30 上进行迭代,并影响 x,即列表中项目的值,而不是列表中的索引。

对于您的情况,您希望使用索引在列表中循环:

index = 0
while index < len(list_30):
  substract = list_30[index] - list_30[index + 1]

编辑:当你到达 list_30 的最后一个元素时,你仍然会遇到问题,因为没有 list_30 [laste_index + 1] 的元素,所以你应该在结束前停止while index < len(list_30) -1:

如果你想要索引和值,你可以这样做:

for i, v in enumerate(list_30):
  substract = v - list_30[i + 1]

但我认为第一个看起来更干净


推荐阅读