我正在努力應對那些「非常明顯我是個白癡」問題。我有一個csv文件,我想閱讀並用它來創建單獨的「表格」。我有一個變量(RID),標誌着一個新的'表'的開始。將字典值分配給變量的問題
我無法讓我的指標變量(currentRow)在我完成操作每一行時前進。你可以看到打印語句,currentRow保持等於0.
但是如果我在循環外使用賦值語句,我可以隨意更改currentRow的值。測試任務只是瞭解我在循環中的位置。
currentRow=0
test=0
theTables=defaultdict(list)
for line in csv.DictReader(open(r'c:\temp\testread.csv')):
newTableKey=line['CIK']+'-'+line['RDATE']+'-'+line['CDATE']+'-'+line['FNAME']+' '+line['TID']
if line['RID']=='1':
test+=1 # I can get here
if currentRow>int(line['RID']):
print 'got here'
theTables[oldTableKey]=theList
test+=1 # I cannot get here
theList=[]
theList.append(line)
currrentRow=int(line['RID'])
print currentRow #this value always prints at 0
print int(line['RID']) #this prints at the correct value
oldTableKey=newTableKey
也許我很困惑,但'row ['RID']'從哪裏來?除了那行,我沒有看到「row」變量。 – Amber 2010-01-01 20:25:25
每一行都是一個字典,在行中有一個叫做RID的鍵(列標題) – PyNEwbie 2010-01-01 20:27:34
你的代碼示例有問題。您正在打印未分配給代碼中任何位置的int(row ['RID'])'。如果它是一個錯字並且你打印int(line ['RID'])並且它與currentRow分配的不同,那麼你還沒有插入所有的代碼;特別是你遺漏了一些重要的東西,它在賦值後再次修改currentRow。 此外,你可以包括CSV格式? – kibitzer 2010-01-01 20:28:28