[英]This program loops the same thing over and over again and I want it to do it once and continuing on to the other programs below the loop
[英]Aparrent looping issue: Why am I appending the same thing to my list over and over again?
我試圖將.csv的每一行轉換成字典(鍵是.csv的第一行),然后試圖將這些字典中的每一個都放入列表中。 當我運行此代碼時,最終還是將.csv的LAST ROW一遍又一遍地添加到列表中,而不是將每個字典(臨時保存為dataLine)正確地添加到列表中? 這更加令人困惑,因為如果我將代碼中的“ dataList.append(dataLine)”行替換為“ print dataLine”,則代碼會在.csv上迭代並單獨打印每一行,而不是一遍又一遍地打印最后一行再次。
from sys import argv
import csv
# arguments
script, csvFile = argv
# check input
while csvFile.endswith(".csv") == False:
csvFile = raw_input("Please enter a *.csv file: ")
# open the csv file
openFile = open(csvFile, 'r')
# read the csv file
reader = csv.reader(openFile, delimiter=',')
# extract first row to use as keys
for row in range(1):
keys = reader.next()
# turn rows into dictionaries with keys
#FIX THIS PART!! NOT WORKING RIGHT!!!
length = len(keys)
dataLine = {}
dataList = []
for row in reader:
for i in range(length):
dataLine[keys[i]] = row[i]
dataList.append(dataLine)
for x in dataList:
print x
print ""
# close the file
openFile.close()
您多次將對同一字典( dataLine
)的引用插入到dataList
。 您一路更改字典的內容,但它仍然是同一對象。
將dataline = {}
移動到您的外部循環中:
for row in reader:
dataLine = {}
您可以嘗試的一件事是在csv
使用內置的DictReader類:
>>> import csv
>>> with open('fake_csv.csv', 'r') as f:
... reader = csv.DictReader(f)
... my_rows = [row for row in reader]
...
>>> my_rows
[{'title1': 'something', 'title2': 'another'}, {'title1': 'cool', 'title2': 'stuff'}]
DictReader
實際上按照您的描述進行操作-它使用第一行作為列標題,並從隨后的每個行創建字典,其中鍵是列標題,值是該行的值。 使用with
是一種確保不再需要文件時將其正確關閉的方法,此行:
my_rows = [row for row in reader]
是一種列表理解 ,它遍歷reader
並將每一行放入結果列表中(標題行除外)。
在這里,我使用了如下所示的CSV:
title1,title2
something,another
cool,stuff
在您的代碼中, dataLine
只是對特定對象的引用。 每次迭代后,此對象都會更改。 因此,列表dataList
存儲相同對象的序列。
使用此代替:
dataLine = {key:row[i] for i, key in enumerate(keys)}
在這種情況下,您需要在每次迭代時創建新的字典。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.