我对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...
....
....所以每次迭代我都在更新字典中所有键的所有值,但是我不知道怎么做。我已经重写过几次了,但现在起作用了。
发布于 2016-06-10 02:07:27
我想出了答案。
紧接此段之前的代码是:
#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)https://stackoverflow.com/questions/37737352
复制相似问题