請耐心等待,我的問題並不像看起來那麼令人望而生畏。一切都很完美,直到第四節結束。如何記錄「n」個數以及相應的時間?初學者任務
def readTemperature():
"""It will read the string, extract the temperature, then return the data
as a float.
"""
data = readTemperatureSensor.randomTemperatureGenerator()
data = str(data)
for line in data:
if "t" in line:
tempBit = data.split("t")
tempString = tempBit[1].replace("=", "")
return float(tempString)/1000
上面的代碼只是讀取溫度。
def getTemperatures(n):
"""Returns a list of floats that contain a certain number (n) of
temperature readings that have been sampled at an interval of one second.
"""
temperaturelist = []
for data in range(n):
temperaturelist.append(float(readTemperature()))
time.sleep(1)
return temperaturelist
上面的代碼得到了一堆相隔一秒的溫度。
def getTimeStamp():
"""Returns the current system date and time as a string with the format
YYYY_MM_DD_HH_MM_SS.
"""
return time.strftime("%Y_%m_%d_%H_%M_%S")
只是一個簡單的時間戳。
現在,我不知道該怎麼做。
def logTemperatures(n):
"""This function will record "n" temperature readings and their
corresponding time-stamps, sampled at 1 seconds intervals.
"""
基本上,它要我創建一個文本文件(這是我能做到),也希望我讀作「n」的溫度和具有它的相應的時間也是如此。如果它只是記錄溫度的設定量,那麼我可以做到這一點,我的代碼是這樣的:
f = open('logTemperatures.txt', 'w')
type(f)
myList = getTemperatures(3)
currentTime = time.time()
f.write(str(time.strftime("%Y_%m_%d_%H_%M_%S",
time.localtime(currentTime - 0.03 * 60))))
f.write(',')
f.write(" ")
f.write(str(myList[0]))
f.write('\n')
f.write(str(time.strftime("%Y_%m_%d_%H_%M_%S",
time.localtime(currentTime - 0.02 * 60))))
f.write(',')
f.write(" ")
f.write(str(myList[1]))
f.write('\n')
f.write(str(time.strftime("%Y_%m_%d_%H_%M_%S",
time.localtime(currentTime - 0.01 * 60))))
f.write(',')
f.write(" ")
f.write(str(myList[2]))
f.close()
logTemperatures(3)
有很多f.write功能,因爲我還是個初學者,但我現在知道我可以使用+按鈕將它鏈接起來。
該文本文件是這樣的:
時間,溫度1
時間+ 1秒,溫度2
時間+ 2秒,溫度3
它可能會達到10個溫度或只有1個。很明顯,上面的代碼不會工作因爲它只會在3個溫度而不是「n」個溫度下進行。我怎樣才能修改它,以便在「n」個溫度下完成?
使用循環,就像你在'getTemperatures(n)'中做的那樣。 –