gpt4 book ai didi

python - 可以让 Counter 不写出 "Counter"吗?

转载 作者:行者123 更新时间:2023-11-28 21:59:46 25 4
gpt4 key购买 nike

因此,当我将计数器(from collections import Counter)打印到一个文件时,我总是得到它的文字 Counter ({'Foo': 12})

有没有办法让计数器不那么字面地写出来?所以它会写 {'Foo' : 12} 而不是 Counter({'Foo' : 12})

是的,这很挑剔,但我厌倦了事后从我的文件中 grep'n 的东西。

最佳答案

您可以将 Counter 传递给 dict:

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 从 构建 dict 时,您不需要额外的临时内存>计数器

关于python - 可以让 Counter 不写出 "Counter"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16095220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com