python - 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)
了另一个错误。
解决方案
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]
但我认为第一个看起来更干净
推荐阅读
- bash - 在 Linux VM 上调用-AzVmRunCommand 以错误的顺序传递参数
- powerbi - Power BI 服务中的数据警报可以发送多封电子邮件吗?
- html - 如何删除 HTML 表格中整个列中的某些字符串?
- java - Java语言中如何连续输入int、double和String?
- typescript - 类型提示来自本地依赖的 Vue 3 全局属性
- windows - 从 powershell 中的计划任务获取更多信息
- arraylist - Groovy - ArrayList 中按键的平均值
- expo - 在 react native WEB 上,如果已安装则打开应用程序,如果未安装,请导航到商店页面
- materialize - Materialize css 不再更新了吗?
- python - 抓取 Coinmarketcap 数据只返回前 10 个结果,为什么其余 90 个不返回?