Python:使用for循环上一次迭代中的float

2024-09-19 23:44:42 发布

您现在位置:Python中文网/ 问答频道 /正文

抱歉,如果这个问题已经在其他地方得到了回答,但我不确定具体的术语可以找到它。你知道吗

我想用这个代码做的是:

  1. 将min(groundtempall)添加到空列表
  2. 对于for循环的每个迭代,将c+groundtempCtext[i-1]添加到groundtempCtext,以便groundtempCtext[i-1]是在上一次迭代中添加的浮点值,或者在第一次迭代的情况下,它是min(groundtempall)。你知道吗

当我试图运行这个我得到的错误。 运行时错误(IndexOutOfRangeException):索引超出范围:1

有谁能提出更好的方法吗/告诉我哪里出了问题谢谢!你知道吗

groundtempCtext = []

groundtempCtext.append(min(groundtempall))

for i in range(1,len(divisionPts1)):
    c = (max(groundtempall)-min(groundtempall))/(len(divisionPts1)-1)
    groundtempCtext.append(c+groundtempCtext[i-1])

groundtempCtext.append(max(groundtempall))

Tags: 代码列表forlen地方错误情况min
2条回答

你可以用列表代替循环。你知道吗

stepSize = (max(groundtempall)-min(groundtempall))/(len(divisionPts1)-1)
groundtempCtext = [min(groundtempall) + ind * stepSize for ind in range(len(divisionPts1))]

我只想记录总数,你可以使用列表comp,但循环更容易理解:

c = (max(ground_temp_all) - min(ground_temp_all)) / (len(division_pts1)-1) # calculate once as it does not change
ground_temp_c_text = [min(ground_temp_all)] # just add min directly to list.
tot = ground_temp_c_text[0]  # set total to  first value in the list
for _ in range(1, len(division_pts1)):
    tot += c # same as adding c to the last value in the list
    ground_temp_c_text.append(tot)

我还将变量改为使用下划线,这是python方法。你知道吗

相关问题 更多 >