簡體   English   中英

字典內部函數未更新(Python)

[英]Dictionary inside function not updating (Python)

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

似乎如果dict卡在某種內存狀態中,則不允許更新它,如果我運行該函數的單個實例(即j = sum_data_by_month('7702010381089',8)II獲得所需的值)。

任何幫助都會非常感激。

謝謝!

字典是可變的

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM