您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

您可以让Counter不写出“ Counter”吗?

您可以让Counter不写出“ Counter”吗?

您可以将传递Counterdict

counter = collections.Counter(...)
counter = dict(counter)
In [56]: import collections

In [57]: counter = collections.Counter(['Foo']*12)

In [58]: counter
Out[58]: Counter({'Foo': 12})

In [59]: counter = dict(counter)

In [60]: counter
Out[60]: {'Foo': 12}

不过,我更喜欢JBernardo的想法:

In [66]: import json

In [67]: counter
Out[67]: Counter({'Foo': 12})

In [68]: json.dumps(counter)
Out[68]: '{"Foo": 12}'

这样,您就不会丢失counter的特殊方法,例如most_common,并且在Python根据构造字典时不需要额外的临时内存Counter

其他 2022/1/1 18:34:11 有472人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶