【问题标题】:how to construct the following dictionary, using List Comprehension?如何使用列表理解构建以下字典?
【发布时间】:2017-05-09 00:41:51
【问题描述】:

您好,我有以下字典:

vocabulary =  {'car': 1, 'read': 3, 'yellow': 2}

weight = [23,445,56]

我想把第一个字典和权重列表关联起来,如下,car这个词的权重是23,因为car这个键的值是一,这个词@的权重987654325@ 是 56 因为是列表权重的第 3 位,最后 yellow 的重量是 2 因为 445 位于列表的第二位,因此我想要的输出是:

vocabulary_weight = {'yellow':445,'read':56,'car':23}

我试过了:

vocabulary_weight = {key: value for (vocabulary.keys(), weight[vocabulary.value()] ) 
                     in vocabulary}

但我得到了:

  File "<ipython-input-7-471237aaf624>", line 7
    vocabulary_weight = {key: value for (vocabulary.keys(), weight[vocabulary.value()] ) in vocabulary}
                                       ^
SyntaxError: can't assign to function call

所以我希望获得支持以实现所需的输出,感谢您的支持,

【问题讨论】:

    标签: python python-3.x dictionary list-comprehension


    【解决方案1】:

    您可以遍历vocabulary.items() 这会将键和值作为元组提供给您。使用key, value 解压并使用value - 1 作为列表的索引:

    >>> vocabulary =  {'car': 1, 'read': 3, 'yellow': 2}
    >>> weight = [23,445,56]
    >>> vocabulary_weight = {key: weight[value - 1] for key, value in vocabulary.items()}
    >>> vocabulary_weight
    {'car': 23, 'read': 56, 'yellow': 445}
    

    【讨论】:

      【解决方案2】:

      这应该可行:

      vocabulary =  {'car': 1, 'read': 3, 'yellow': 2}
      weight = [23,445,56]
      
      vocabulary_weight = {key : weight[int(vocabulary[key]) - 1] for key in vocabulary.keys()}
      

      【讨论】:

        猜你喜欢
        • 2013-10-07
        • 2016-06-09
        • 2018-06-21
        • 2017-02-14
        • 2020-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-16
        相关资源
        最近更新 更多