【问题标题】:Saving a variable and a constant in a dictionary on Python在 Python 的字典中保存变量和常量
【发布时间】:2015-09-14 12:21:50
【问题描述】:

所以我在 Python 上编写代码,但我对该语言了解不多,所以我遇到了一些问题。我想做的是: 例如,我有一个音乐流派列表(摇滚、流行、嘻哈)和一个分类列表(坏、好、正常),我有一个字典(genredict),我想做的是当我跑步时我的代码,每次它达到一种类型时,我都会得到它的分类并增加一个。比如:

    genredict['rock'] = 'good', ++1 'something like this, for sure this part won't work'

我曾考虑为每种类型创建一个字典,但我的列表中有很多类型,所以这不是解决问题的最佳方法。所以有谁知道我怎样才能在字典中保存一个键和多个值,其中一个值可以递增而另一个值是常数?

感谢大家的帮助。

【问题讨论】:

  • 为每个类型创建一个键,当类型匹配时增加值。

标签: python dictionary


【解决方案1】:

我会使用嵌套字典,最简单的实现方法是使用 defaultdictCounter

>>> from collections import Counter, defaultdict
>>> genredict = defaultdict(Counter)
>>> genredict
defaultdict(<class 'collections.Counter'>, {})  # starts off empty
>>> genredict['rock']['good'] += 1  # increment appropriate genre/rating
>>> genredict['blues']['normal'] += 1
>>> genredict
defaultdict(<class 'collections.Counter'>, 
            {'blues': Counter({'normal': 1}), 'rock': Counter({'good': 1})})
>>> genredict['rock']['good']  # retrieve current score
1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 2013-01-28
    • 1970-01-01
    相关资源
    最近更新 更多