首页 > 解决方案 > Python3 - 在内部循环中更新“power”变量会修改外部循环的聚合变量

问题描述

我通读了目录中的所有文件(csv 文件) - 我忽略了每个文件的前 7 个“标题”行,然后从第 8 行到第 151 行找到时间和功率值。我读到的每一行都是形式[示例行 6-9 和 46-48]

Time;Power
HH:mm;kW
00:10;0.000
00:20;0.000
<snip>
06:20;0.012
06:30;0.042
06:40;0.060

我的代码成功地忽略了所有午夜后的零读数,并正确识别了 06:20 的第一个非零功率读数。它使用时间(小时和分钟)来调整包含当天时间戳的变量,并将现在的小时/分钟包含时间戳和功率存储在复杂变量中timePower[(timestamp),(power)] 然后将变量附加timePower[(),()]到变量dayPower[]并再次开始文件的下一行。

由于某种原因我无法解决,下一行解析得很好,直到我timePower[0]用新的时间戳和timePower[1]新的权力更新 - 更新这些变量似乎也更新了dayPower[]变量(dayPower[0])中的现有条目,现在,就在之前我即将追加一个新条目,旧条目看起来与新条目相同。新行成功追加。这种错误行为会一直重复,直到我读完所有非零值并且所有行dayPower[]看起来都与最终条目相同。相关功能如下:

def parse_power_values(path, filename, theDate):
  timePower = [(),()] #a list that will be assigned two items; the timestamp and the power for that timeslot
  dayPower = [] # A list that will have all the timePowers for the day appended
  currentFile = open(path + filename,'r')
  for i, line in enumerate(currentFile):
    if i <= 7:
      doingSomething = True
      #print 'header' + str(i) + '/ ' + line.rstrip()
    elif ((i > 7) and (i <= 151)):
      lineParts = line.split(';')
      theTime = lineParts[0].split(':')
      theHour = theTime[0]
      theMin = theTime[1]
      timestamp = theDate.replace(hour=int(theHour),minute=int(theMin)) #theDate is a timestamp obj with the current date but hour & minute at 00:00 to start with.
      power = lineParts[1].rstrip()
      if power == '-.---':
        power = 0.000
      if (float(power) > 0):
        #append_to_database(con, timestamp,power)
        timePower[0] = timestamp
        timePower[1] = power
        dayPower.append(timePower)
    elif i > 151:
     return dayPower
     #break
  currentFile.close()

标签: python

解决方案


@jasonharper 是对的,我修改后的函数现在看起来像这样:

def parse_power_values(path, filename, theDate):
  # timePower = [(),()] #a list that will be assigned two items; the timestamp and the power for that timeslot
  dayPower = [] # A list that will have all the timePowers for the day appended
  currentFile = open(path + filename,'r')
  for i, line in enumerate(currentFile):
    if i <= 7:
      doingSomething = True
      #print 'header' + str(i) + '/ ' + line.rstrip()
    elif ((i > 7) and (i <= 151)):
      lineParts = line.split(';')
      theTime = lineParts[0].split(':')
      theHour = theTime[0]
      theMin = theTime[1]
      timestamp = theDate.replace(hour=int(theHour),minute=int(theMin))
      power = lineParts[1].rstrip()
      if power == '-.---':
        power = 0.000
      if (float(power) > 0):
        dayPower.append([timestamp,power])
    elif i > 151:
     return dayPower
     #break
  currentFile.close()

推荐阅读