【问题标题】:How to convert Counter object dict to string如何将 Counter 对象字典转换为字符串
【发布时间】:2020-03-13 07:54:03
【问题描述】:

在 Python 中有没有办法将 Counter 字典转换为字符串?

我尝试过 str(counterobj) 方法,但 Counter 不支持(来自集合库)

谢谢!!

【问题讨论】:

  • 你试过help(myCounterDict)吗?
  • 您希望它看起来如何?您能否提供所需格式的示例?它会像普通字典的str 一样吗? Counter支持str,但是不是你想要的格式吗?
  • str(counterobj) 遇到了什么问题?
  • 嗨,我的输出很差。它仍然输出正常的 Counter[{Key:Value}] 而不是正常的 [Key, Value, Key, Value]

标签: python string dictionary collections


【解决方案1】:

你可以用这个:

str(dict(Counter([1,3,4,5,6,4,334,4,4,4,3,2,5,4,2])))                                                                                                                                              
# '{1: 1, 3: 2, 4: 6, 5: 2, 6: 1, 334: 1, 2: 2}'

【讨论】:

    【解决方案2】:

    如果你想要一个由键的频率组成的字符串,你可以

    " ".join(Counter(map(str, [1, 2, 3, 3, 2])).elements())

    然后得到:

    1 2 2 3 3

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-16
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2020-12-29
      • 2018-07-19
      相关资源
      最近更新 更多