【问题标题】:Overwriting all values while iterating a for loop- Python在迭代 for 循环时覆盖所有值 - Python
【发布时间】:2016-10-10 18:41:43
【问题描述】:

我是 python 新手,一直致力于解析 Excel 电子表格。我正在尝试确定与一系列日期的特定分区相关的累积值。

我有一种感觉,我没有正确理解逻辑流程,因为无论我如何编写它,我总是得到一个完全相同的值字典。在这一点上,我不知道为什么它是错误的,所以我不想围绕它写,而是想直面它。

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...
....
....

所以我在每次迭代时都会以某种方式更新字典所有键的所有值,但我只是看不出如何。我已经重写了几次,现在可以使用了。

【问题讨论】:

    标签: python list python-2.7 for-loop dictionary


    【解决方案1】:

    我想出了答案。

    该段之前的代码是:

    #Set structure of hoursAllocationDict
    #Date:
    #        Zoning1: 0
    #        Zoning2: 0
    
    for date in uniqueDateList:
        hoursAllocationDict[date] = zoningsDict
    

    看看 Python 如何处理赋值(来自 8.17 “copy”):

    Python 中的赋值语句不会复制对象,它们会在目标和对象之间创建绑定。对于可变集合或包含可变项的集合,有时需要一个副本,以便可以更改一个副本而不更改另一个副本。

    将上述代码更改为以下代码解决了该问题:

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

    【讨论】:

      猜你喜欢
      • 2014-11-25
      • 2016-07-17
      • 1970-01-01
      • 2012-06-27
      • 2023-03-05
      • 1970-01-01
      • 2019-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多