我在寫一個Python腳本,它讀取一個CSV文件並創建一個deques列表。如果我打印出在添加之前附加到列表中的內容,它看起來就像我想要的,但是當我打印列表本身時,我可以看到附加內容正在用最新的內容覆蓋列表中的所有元素。爲什麼追加用新元素覆蓋列表中的所有內容?
# Window is a list containing many instances
def slideWindow(window, nextInstance, num_attributes):
attribute = nextInstance.pop(0)
window.popleft()
for i in range(num_attributes):
window.pop()
window.extendleft(reversed(nextInstance))
window.appendleft(attribute)
return window
def convertDataFormat(filename, window_size):
with open(filename, 'rU') as f:
reader = csv.reader(f)
window = deque()
alldata = deque()
i = 0
for row in reader:
if i < (window_size-1):
window.extendleft(reversed(row[1:]))
i+=1
else:
window.extendleft(reversed(row))
break
alldata.append(window)
for row in reader:
window = slideWindow(window, row, NUM_ATTRIBUTES)
alldata.append(window)
# print alldata
f.close()
return alldata
備註:當您使用'with open(...)'時,您不需要關閉文件。事實上,這是上下文管理者的優勢之一。 – delnan 2012-08-10 02:20:07