Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

Python ( iteration problem ) with an exercice

The code :

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))

Hey guys ! i'm really having trouble with the black part.

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

I'm trying to iterate over the elements and sub stracting element x with the next element (x+1) but the following error pops out TypeError: 'float' object is not iterable. I have also tried to iterate using x instead of list_30[x] but then when I use next(x) I have another error.

question from:https://stackoverflow.com/questions/65940253/python-iteration-problem-with-an-exercice

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

for x in list_30: will iterate on list_30, and affect to x, the value of the item in the list, not the index in the list.

for your case you would prefer to loop on your list with indexes:

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

edit: you will still have a problem when you will reach the last element of list_30 as there will be no element of list_30[laste_index + 1], so you should probably stop before the end with while index < len(list_30) -1:

in case you want the index and the value, you can do:

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

but the first one look cleaner i my opinion


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...