【问题标题】:How can I print two counter side by side in python?如何在 python 中并排打印两个计数器?
【发布时间】:2019-12-27 13:49:41
【问题描述】:

我有一个这样的函数。我需要在python中并排打印两个字典。

def kelime_sayma(metin):
    kelimeler = metin.split()
    kelime_sayi = Counter(kelimeler)

    for i,value in kelime_sayi.most_common():
        print('{}    {}'.format(i, value))
    for j,value in sorted(kelime_sayi.items()):
        print('{}    {}'.format(j, value))

【问题讨论】:

  • 您使用的是collections.Counter 还是其他?你能告诉我们metin arg 的内容吗?
  • metin 的预期输入是什么?
  • 您的预期输出是什么?并排是什么意思?
  • 是的,我正在使用 collections.Counter @EnriqueBermúdez
  • metin 是来自用户的文本。我需要一个程序来打印文本中单词的使用次数。 @DeveshKumarSingh

标签: python python-3.x dictionary printing


【解决方案1】:

你可以试试:

>>> a
['c', 'a', 'b', 'b', 'c', 'b', 'b', 'b', 'a', 'a', 'b', 'a', 'b', 'c', 'c', 'a', 'c', 'a', 'a', 'b', 'a', 'a', 'c', 'a', 'b', 'c', 'c', 'c', 'b', 'a']
>>> b=Counter(a)
>>> b
Counter({'a': 11, 'b': 10, 'c': 9})
>>> for i,j in zip(b.most_common(), b.items()):
...     print('{} {} {} {}'.format(i[0], i[1], j[0], j[1]))

输出

a 11 c 9
b 10 a 11
c 9 b 10

【讨论】:

    【解决方案2】:

    问题:并排打印两个字典

        for i, v1, v2 in enumerate(zip(kelime_sayi.most_common(), sorted(kelime_sayi.items()), 1):
            print('{}    {} {}'.format(i, v1, v2))
    

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 2022-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-01
      • 2020-07-17
      相关资源
      最近更新 更多