我正在编写一个Python脚本,该脚本读取CSV文件并创建双端队列.如果我精确地打印出添加到列表之前要追加到列表中的内容,则看起来像我想要的,但是当我打印出列表本身时,我可以看到append用最新元素覆盖了列表中的所有元素.
# 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
解决方法:
很难从此代码中跟踪您到底想要什么.我怀疑问题出在以下方面:
alldata.append(window)
for row in reader:
window = slideWindow(window, row, NUM_ATTRIBUTES)
alldata.append(window)
请注意,在slideWindow函数中,您修改了输入双端队列(窗口),然后返回修改后的双端队列.因此,您将双端队列放入列表的第一个元素中,然后修改该对象(在slideWindow内部),然后将对同一对象的另一个引用附加到列表中.
那是你打算做的吗?
简单的解决方法是复制在slideWindow中输入的窗口并修改/返回副本.