2016-06-09 90 views
0

我是python的新手,一直致力於解析excel電子表格。我試圖確定一系列日期的特定分區的累計值。在迭代for循環時覆蓋所有值 - Python

我有一種感覺,我沒有正確理解邏輯流程,因爲不管我如何寫它,我總是以一個完全相同的值的字典結尾。在這一點上,我不明白爲什麼它是錯誤的,所以我不想寫它,而是想面對它。

的hoursAllocationDict樣子:

5-21-16 
    Zoning1: 0 
    Zoning2: 0 
    Zoning3: 0 
5-22-16 
    Zoning1: 0 
etc... 

我RAWDATA看起來像一個列表的列表:

[0] NAME, data, data, data, DATE, data, HOURS, data, ZONING, data, data, data, etc. 
[1] NAME, data, data, data, DATE, data, HOURS, data, ZONING, data, data, data, etc. 
[2] NAME, data, data, data, DATE, data, HOURS, data, ZONING, data, data, data, etc. 

我競選這一特定任務的代碼塊的樣子:

#Iterate over all dates - date is a tuple with 0 index being the date and 1 being a dict of zonings 
for date in hoursAllocationDict.iteritems(): 

    #Iterate over each row 
    for row in rawData: 

     #If cell is not empty or blank AND if date cell equals iterator date 
     if rawData[row][23] and rawData[row][9] == date[0]: 

      #Use re.search to match possible zoning in zoning column (found in string of otherwise irrelevant data) 

      if findZoningInCell(rawData[row][23], zoningsDict): 


       #Store whatever subjoining we find 
       subZoning = findZoningInCell(rawData[row][23], zoningsDict) 

       #rawData[row][18] references a value of hours related to zoning 

       #Accumulate x.x hrs in hoursAllocationDict -> date -> subjoining 

       hoursAllocationDict[rawData[row][9]][subZoning] += rawData[row][18] 

hoursAllocationDict的最終狀態如下所示:

'10-29-15' : 'Zoning1': 52.0, 'Zoning2': 100.08333333333333, 'Zoning3': 128.0, 'Zoning4': 594.0, etc... 
'10-30-15' : 'Zoning1': 52.0, 'Zoning2': 100.08333333333333, 'Zoning3': 128.0, 'Zoning4': 594.0, etc... 
'10-31-15' : 'Zoning1': 52.0, 'Zoning2': 100.08333333333333, 'Zoning3': 128.0, 'Zoning4': 594.0, etc... 
.... 
.... 

所以我不知何故每次迭代更新字典的所有鍵的所有值,但我不知道如何。我已經重寫了幾次,現在可以利用。

回答

0

我想出了答案。

緊接本段之前的代碼是:

#Set structure of hoursAllocationDict 
#Date: 
#  Zoning1: 0 
#  Zoning2: 0 

for date in uniqueDateList: 
    hoursAllocationDict[date] = zoningsDict 

Python處理分配看(從8.17 「拷貝」):在Python

賦值語句不復制的對象,他們創造目標和對象之間的綁定。對於可變項目或包含可變項目的集合,有時需要副本,以便可以更改一個副本而不更改其他副本。

更改上面的代碼下面的解決了這個問題:

from copy import copy 

.... 

for date in uniqueDateList: 
    hoursAllocationDict[date] = copy(zoningsDict)