在迭代for循环Python时重写所有值

2024-05-16 03:32:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,一直致力于分析excel电子表格。我试图确定一个特定分区在一系列日期内的累计价值。在

我有一种感觉,我没有正确理解逻辑流程,因为不管我怎么写,我总是得到一本价值观都一样的字典。在这一点上,我没有直觉来解释为什么它是错的,所以我不想围绕它写作,而是想正面面对它。在

工时分配ICT看起来像:

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

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

^{pr2}$

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

#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]

小时分配ict的最终状态如下:

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

所以每次迭代我都会更新字典中所有键的所有值,但是我不知道如何更新。我已经重写了几次,现在有用了。在


Tags: ofin列表dateif字典etcrow
1条回答
网友
1楼 · 发布于 2024-05-16 03:32:54

我找到了答案。在

此段前面的代码是:

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

for date in uniqueDateList:
    hoursAllocationDict[date] = zoningsDict

看看Python如何处理赋值(从8.17“copy”开始):

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.

将上述代码更改为以下代码可解决此问题:

^{pr2}$

相关问题 更多 >