python - 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()
解决方案
@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()
推荐阅读
- c++ - 尽管是错误的,但循环不会退出
- firebase - 颤振格式异常:意外字符(在字符 1 处)
- c - 如何在运行时解析 dll 中的外部符号,而不是使用 Cygwin 进行链接时
- python - 为什么不能将值输入 TensorFlow 中的“placeholder_with_default”?
- c++ - 为什么在“B”类的源文件中导入“A”类的头文件会使“A”类的内容定义在“B”类的头文件中?
- javascript - 如何在模态之外使用 handleClick 关闭模态?
- random - 邮递员 - 锁定随机值,同一集合中的每个测试的值相同
- javascript - 使用 expo 将图片保存到 mediaLibrary 的问题
- neo4j - 密码按相关节点数排序?
- c++ - 将整数转换为 std::list 的迭代器