我是 stackoverflow 和 Python 的新手。几天来我一直在努力让它工作,但我不太明白我做错了什么,而且我已经搜索了很多常见问题但没有运气。
以下代码从 csv 文件中读取一些销售数据,然后返回一个包含两个键(唯一代码和年份值)和特定月份销售额总和的字典。我将两个参数传递给函数,代码和月份。那部分正在做我想做的事情,当我想在不同的月份进行迭代时,问题就来了,无论我为函数分配什么值(月份),它总是会返回我分析的第一个值
d = defaultdict(int)
spamReader = csv.reader(open('C:\Sales\Sales_CO05.csv', 'rU'))
#Return the sales sum for a given month and code
def sum_data_by_month(ean, m):
for line in spamReader:
tokens = [t for t in line]
if tokens[5] == str(ean):
try:
sid = tokens[5]
dusid = tokens[18]
value = int(str(tokens[m]).replace(',',''))
except ValueError:
continue
d[sid,dusid] += value
return d
#Try to iterate over different month values
j = sum_data_by_month('7702010381089', 6)
f = sum_data_by_month('7702010381089', 7)
m = sum_data_by_month('7702010381089', 8)
a = sum_data_by_month('7702010381089', 9)
这是我得到的结果:
defaultdict(<type 'int'>, {('7702010381089', '2013'): 80, ('7702010381089', '2014'): 363})
defaultdict(<type 'int'>, {('7702010381089', '2013'): 80, ('7702010381089', '2014'): 363})
defaultdict(<type 'int'>, {('7702010381089', '2013'): 80, ('7702010381089', '2014'): 363})
defaultdict(<type 'int'>, {('7702010381089', '2013'): 80, ('7702010381089', '2014'): 363})
这就是我所期待的:
defaultdict(<type 'int'>, {('7702010381089', '2013'): 80, ('7702010381089', '2014'): 363})
defaultdict(<type 'int'>, {('7702010381089', '2013'): 229, ('7702010381089', '2014'): 299})
etc..
似乎如果字典卡在某种不允许更新的内存状态,如果我运行该函数的单个实例(即 j = sum_data_by_month('7702010381089', 8)I 我得到 de期望值。
我们将不胜感激任何帮助。
谢谢!
请您参考如下方法:
字典是可变的
j = sum_data_by_month('7702010381089', 6)
j is d # true
不创建新字典...它只是指向现有字典
f = sum_data_by_month('7702010381089', 7) #the dictionary has changed
f is j # true , both point to the same dictionary
f is d # true , both point to d to be specific
你可以通过以下方法修复它
from copy import deepcopy
...
def sum_data_by_month(ean, m):
...
return deepcopy(d) # a new dict no longer just a pointer to the same d
#or maybe even better
return dict(d)
现在
j = sum_data_by_month('7702010381089', 6)
j is d # false
