【问题标题】:Accessing specific values of a loop-created dictionary in a Python function在 Python 函数中访问循环创建的字典的特定值
【发布时间】:2013-02-22 00:06:46
【问题描述】:

我对 Python 非常陌生,作为练习,我尝试使用代码解决基本的金融练习。我的目标是获得一本即期汇率字典,然后是从中计算出的贴现率字典。我曾想过这样的事情:

discountrates={}

def discountrates(n):
    spotrates={}
    for x in range(1,n+1):
        spotrates['s'+str(x)]=float(input('What is s'+str(x)+'? (not in percentage)'))
    for y in range(1,n+1):
         discountrates['d(0,'+str(y)+')']= 1/((1+float(spotrates['s'+str(y)]))**y)
    for key, value in discountrates.items():
        print (key, value) 

现在的问题是无法在函数中访问字典项。当我查看您的论坛时,我找到了解压缩字典的解决方案,但这在我的情况下不起作用,因为我需要访问字典的特定元素,其名称无法完全指定(正如我在 Python 手册中看到的那样)因为它是循环的一部分,为了使公式能够工作而无需手动插入任何其他内容。我首先使用字典来创建自动生成的名称,但现在我似乎无法从中获取信息。

什么是最好的解决方案?

提前感谢您的帮助。这让我快疯了。

【问题讨论】:

    标签: python function loops dictionary


    【解决方案1】:

    这是因为您调用了全局变量 discountratesdict 而不是 discountrates(这是您的函数的名称)。

    【讨论】:

      【解决方案2】:

      我建议你不要像你的函数一样命名你的字典,因为后者会覆盖前者。在第 1 行你说 discountrates 是一个空的 dict,在第 2 行你说 discountrates 是一个函数对象. 如果它们在同一范围内,则需要在 python 中给它们起不同的名称。

      此外,为什么需要 discountrates 成为 global?如果n 比以前的n 小,您愿意保留旧费率吗?为了性能,我建议您将两个循环结合起来。除此之外,没有理由为什么第二个循环也不能读取for x ...,因为 zou 无论如何都不再使用 x 了。作为进一步的提示,如果您得出结论,全局是唯一可能有助于添加 global discountratesdict 的方法,因此更容易发现全局是用于此处的,即使这在您的特定情况下不是必需的case 因为[]-operator 需要一个对象,因此它已经引用了您的全局。

      将所有这些放在一起产生:

      discountratedict={}
      
      def discountrates(n):
          global discountratedict
          spotrates={}
      
          for x in range(1,n+1):
              spotrates['s'+str(x)]=float(input('What is s'+str(x)+'? (not in percentage)'))
              discountratedict['d(0,'+str(x)+')']= 1/((1+float(spotrates['s'+str(x)]))**x)
      
          for key, value in discountratedict.items():
              print (key, value) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-04
        • 2019-03-01
        • 2019-02-03
        • 2018-10-06
        • 2014-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多