[英]How to append items into a 2D list?
我有一個二維列表趨勢。 我通過文件夾中的每個文件(主要是 CSV 文件)打開一個文件夾和 go。 對於每個文件,我想將數據放入列表第一維的新插槽中。 對於文件中的每一行,我想將數據放入列表第二維的新槽中。 我在這里做錯了什么?
def showTrends():
trends = [[]]
folder = filedialog.askdirectory()
fileNum = 0
for file in os.listdir(folder):
if not "data.csv" in file and not ".gitkeep" in file:
with open("data/" + file) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count != 0:
trends[fileNum[line_count]].append(row[1])
line_count += 1
csv_file.close()
fileNum += 1
print(trends)
我建議首先創建內部數組,然后將其作為一個整體附加到外部數組,如下所示:
trends = []
for file in files:
file_result = []
with open(file) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
next(csv_reader) # To skip the header
for row in csv_reader:
file_result.append(row[1])
trends.append(file_result)
這樣,您根本不需要保留計數器,並且您的代碼將更易於閱讀。
如果您使用上下文管理器( with
語句),您也不需要關閉文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.