首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在迭代for循环- Python时覆盖所有值

在迭代for循环- Python时覆盖所有值
EN

Stack Overflow用户
提问于 2016-06-09 22:41:48
回答 1查看 1.4K关注 0票数 0

我对python很陌生,并且一直致力于解析excel电子表格。我试图通过一系列的日期来确定与特定分区相关的累计值。

我有一种感觉,我没有正确地理解逻辑流,因为无论我怎么写它,我最终都会得到一本相同的值字典。在这一点上,我没有直觉,为什么它是错误的,所以我不想写它周围,我想面对它正面。

hoursAllocationDict看起来像:

代码语言:javascript
复制
5-21-16
    Zoning1: 0
    Zoning2: 0
    Zoning3: 0
5-22-16
    Zoning1: 0
etc...

我的rawData看起来像一个列表:

代码语言:javascript
复制
[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. 

我为这个特定任务运行的代码块如下所示:

代码语言:javascript
复制
#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的最终状态如下所示:

代码语言:javascript
复制
'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...
....
....

所以每次迭代我都在更新字典中所有键的所有值,但是我不知道怎么做。我已经重写过几次了,但现在起作用了。

EN

回答 1

Stack Overflow用户

发布于 2016-06-10 02:07:27

我想出了答案。

紧接此段之前的代码是:

代码语言:javascript
复制
#Set structure of hoursAllocationDict
#Date:
#        Zoning1: 0
#        Zoning2: 0

for date in uniqueDateList:
    hoursAllocationDict[date] = zoningsDict

查看Python如何处理赋值(来自8.17 "copy"):

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

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

代码语言:javascript
复制
from copy import copy

....

 for date in uniqueDateList:
    hoursAllocationDict[date] = copy(zoningsDict)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37737352

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档