字典被视为NoneType(Python 3.5.1)

时间:2016-05-05 11:35:23

标签: python python-3.x dictionary nonetype stocks

from statistics import stdev

data = [line.rstrip('\n').split(',') for line in open('C:/Users/User/Downloads/documents-export-2016-05-04/Data.csv')]
dates = list(open('C:/Users/User/Downloads/documents-export-2016-05-04/Dates.csv').read().split('\n'))
stock_values = [int(x) for x in open('C:/Users/User/Downloads/documents-export-2016-05-04/stock_value.csv').read().split(',')]
companies = open('C:/Users/User/Downloads/documents-export-2016-05-04/companies.csv').read().split(',')
prices = dict(zip(companies, stock_values))

PRICE = 0
old_volatility = 0
new_volatility = 0

def get_change(values, invested):
    sum_product = ([x * y for x, y in zip(values, invested)])
    return(sum(sum_product) / sum(invested))


def get_volatility(invested):
    changes = {}
    for i, j in enumerate(list(reversed(dates))):
        changes[j] = get_change(list(map(float, data[i])), invested.values())
    vals = changes.values()
    volatility = stdev(vals)
    return volatility


def tuner(invested, company):
    global PRICE
    global old_volatility

    temp_invested = invested.copy()
    temp_invested[company] += 1
    new_volatility = get_volatility(temp_invested)
    new_price = PRICE + prices[company]
    if new_volatility - old_volatility < -0.01 and new_price <= BUDGET:
        old_volatility = new_volatility
        PRICE = new_price
        tuner(temp_invested, company)
    else:
        return invested


if __name__ == "__main__":
    BUDGET = int(input())

    invested = {}
    for company in companies: invested[company] = 0
    invested['A'] = 1
    old_volatility = get_volatility(invested)

    for company in companies:
        if PRICE < BUDGET:
            invested = tuner(invested, company)
        else:
            break
    print("Price = ", PRICE)
    print("Volatility = ", old_volatility)

出于某种原因,在上面的代码中,经过3次迭代的for循环“for company in companies”,我得到一个错误,上面写着“'NoneType'对象没有属性'copy'”,指的是字典“投资” ”。我不明白为什么经过几次迭代后,字典会突然被视为NoneType。原始数据只是作为字符串列表读入,因此它们并不重要。任何帮助表示赞赏。感谢。

1 个答案:

答案 0 :(得分:4)

您的tuner函数中的一个分支不会返回任何内容,因此在执行该分支时,投资将设置为None