Python3 - 更新内部循环中的"power"变量会修改外部循环的聚合变量



我通读了一个目录中的所有文件(csv文件(-我忽略了每个文件的前7行"header",然后找到从第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()

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

最新更新