【问题标题】:How to assing values to a dictionary如何为字典赋值
【发布时间】:2017-10-12 21:17:43
【问题描述】:

我正在创建一个函数,它应该返回一个字典,其中包含来自不同列表的键和值。但是我在将列表的平均值作为字典的值时遇到了问题。但是,我认为我得到了正确的钥匙。 这是我目前得到的:

 def exp (magnitudes,measures):
   """return for each magnitude the associated mean of numbers from a list"""
dict_expe = {}
for mag in magnitudes:
    dict_expe[mag] = 0
    for mea in measures:
        summ = 0
    for n in mea:
        summ += n
        dict_expe[mag] = summ/len(mea)


        return dict_expe

print(exp(['mag1', 'mag2', 'mag3'], [[1,2,3],[3,4],[5]]))

输出应该是:

{mag1 : 2, mag2: 3.5, mag3: 5}

但我得到的总是 5 作为所有键的值。我考虑了 zip() 方法,但我试图避免它,因为它在两个列表中需要相同的长度。

【问题讨论】:

    标签: python-3.x dictionary key-value-store


    【解决方案1】:

    序列的平均值为sum(sequence) / len(sequence),因此您需要遍历magnitudesmeasures,计算这些均值(算术平均值)并将其存储在字典中。

    还有更多的 Pythonic 方法可以实现这一点。所有这些示例都会生成 {'mag1': 2.0, 'mag2': 3.5, 'mag3': 5.0} 作为结果。

    使用for i in range()循环:

    def exp(magnitudes, measures):
        means = {}
        for i in range(len(magnitudes)):
            means[magnitudes[i]] = sum(measures[i]) / len(measures[i])
        return means
    
    print(exp(['mag1', 'mag2', 'mag3'], [[1, 2, 3], [3, 4], [5]]))
    

    但如果您需要列表的索引和值,您可以使用for i, val in enumerate(sequence) 方法,这在这种情况下更合适:

    def exp(magnitudes, measures):
        means = {}
        for i, mag in enumerate(magnitudes):
            means[mag] = sum(measures[i]) / len(measures[i])
        return means
    
    print(exp(['mag1', 'mag2', 'mag3'], [[1, 2, 3], [3, 4], [5]]))
    

    另一个问题隐藏在这里:i 索引属于magnitudes,但我们也使用它从measures 获取值,如果你有magnitudesmeasures,这对你来说没什么大不了的长度相同,但如果magnitudes 更大,您将获得IndexError。所以在我看来,使用 zip 函数是最好的选择(实际上从 python3.6 开始,它不需要两个列表的长度相同,它只会使用最短的一个作为结果的长度):

    def exp(magnitudes, measures):
        means = {}
        for mag, mes in zip(magnitudes, measures):
            means[mag] = sum(mes) / len(mes)
        return means
    
    print(exp(['mag1', 'mag2', 'mag3'], [[1, 2, 3], [3, 4], [5]]))
    

    所以请随意使用适合您要求的示例,不要忘记添加文档字符串。

    您可能不需要这样的pythonic方式,但当字典理解发挥作用时,它可能会更短:

    def exp(magnitudes, measures):
        return {mag: sum(mes) / len(mes) for mag, mes in zip(magnitudes, measures)}
    
    print(exp(['mag1', 'mag2', 'mag3'], [[1, 2, 3], [3, 4], [5]]))
    

    【讨论】:

      猜你喜欢
      • 2019-05-14
      • 1970-01-01
      • 2016-09-14
      • 2020-07-28
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 2020-10-28
      相关资源
      最近更新 更多