我正在尝试将所有已处理列表(删除的空白列表项,删除的所有\n
和\r
等)添加到名为allOrders
的空白列表中。问题是执行代码后,allOrders
仅包含作为最后一个追加的列表。
import os
if orderFilesListCount >= 1:
for singleOrderFile in orderFilesList: # does the following to all Orders in OrderFileList
orderContents = list() # creates empty list
dataRemoveSpaces = list() # creates empty list
allOrders = list() # creates empty list
f = open(os.path.join(directory, singleOrderFile), "rb") # opens each order file
data = f.read().decode("utf16") # decodes data from file
dataRemoveLine = data.rstrip().split('\n') # removes new lines
dataRemoveTabs = [s.strip('\r') for s in dataRemoveLine] # removes all /r from list items
dataRemoveEmpty = list(filter(None, dataRemoveTabs)) # removes all empty list items
for element in dataRemoveEmpty: # following code trimms all elements in list
element = element.strip()
dataRemoveSpaces.append(element) # add trimmed elements back to list
print(dataRemoveSpaces) # my verification if the list was sucessfuly processed
allOrders.append(dataRemoveSpaces) # appends allOrders list with processed list
我知道一个事实,即不是代码可以“处理”每个单独的列表(感谢最后一个print
-它看起来应该完全一样)。
这是什么问题?我见过几个处理类似问题但无法将其解决方案应用于我的线程。
答案 0 :(得分:2)
输入行:
allOrders = list()#creates empty list
退出for循环,因为您迭代的每一步都在创建一个空列表,因此您只有最后一个列表
答案 1 :(得分:1)
您每次迭代都重新创建allOrders
:
allOrders = list()#creates empty list
因此您将其擦除。在if语句中将此行移出循环:
if orderFilesListCount >= 1:
allOrders = list() # <------------------- HERE
for singleOrderFile in orderFilesList:
或者甚至是if语句:
allOrders = list() # <------------------- HERE
if orderFilesListCount >= 1:
for singleOrderFile in orderFilesList:
因此您将不会不断擦除它。