【问题标题】:Dictionary being treated as NoneType (Python 3.5.1) [duplicate]字典被视为 NoneType (Python 3.5.1) [重复]
【发布时间】:2016-05-05 11:35:22
【问题描述】:
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)

由于上述代码中的某些原因,在 for 循环“for company in Companies”的 3 次迭代后,我收到一条错误消息,指出“'NoneType' 对象没有属性 'copy'”,指的是字典 'invested '。我不明白为什么经过几次迭代后,字典会突然被视为 NoneType。原始数据只是作为字符串列表读入,所以它们并不重要。任何帮助表示赞赏。谢谢。

【问题讨论】:

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


    【解决方案1】:

    tuner 函数中的一个分支不会返回任何内容,因此当该分支被采用时,投资会设置为 None

    【讨论】:

    • 但是tuner 的另一个分支递归地调用自己,我从数据中知道else 分支最终必须被采用,所以它会返回invested。此外,少数有效的迭代实际上采用了前一个分支。
    • @ENPM 它递归调用自身,但它不返回从该递归调用中获得的值。
    猜你喜欢
    • 2015-07-11
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 2020-06-14
    • 2014-01-03
    • 1970-01-01
    • 2015-02-21
    • 2016-12-06
    相关资源
    最近更新 更多