【问题标题】:Counting distinct elements and their frequency short method using collections.Counter()使用 collections.Counter() 计算不同元素及其频率短方法
【发布时间】:2021-09-11 20:09:15
【问题描述】:

输入-

第一行包含整数 n。 接下来的 n 行每行包含一个单词。

4
abc
abcdef
abcd
abc

输出-

输出 2 行。 在第一行,输出输入中不同单词的数量。 在第二行,根据每个不同单词在输入中的出现输出其出现次数。

3
2 1 1

这是我的代码-

import collections
n=int(input())
l=[]
l1=[]
for i in range(n):
    st=input()
    l1.append(st)
    if st not in l:
     l.append(st)
frequency = collections.Counter(l1)
d=dict(frequency)
print(len(l))
for i in d.values():
  print(i,end=" ")

有没有更短的方法可以做到这一点,使用单个列表而不是创建两个(l 和 l2)。

【问题讨论】:

  • @DanielHao ya 我当然愿意。
  • 我看到答案被接受,所以我会通过。
  • @DanielHao 不,实际上我没有。
  • 我想通过专门使用 collections.Counter() 来做到这一点。

标签: python-3.x dictionary collections counter


【解决方案1】:

您可以尝试此示例并对其进行修改以满足您的要求以获得所需的输出。它只使用了一个列表,而不是两个。但是,我留出一步 故意,以便您可以改进和练习。只需尝试输入相同的示例输入,看看输出是什么。

from collections import Counter

N  =  int(input('Number of words: (one per line)'))  # how many numbers of words, eg. 5

l1  =  []

#for i in range(N):
ll = [input() for _ in range(N) ]  # get all words, one per line
      
#frequency =  Counter(l1)

counts = Counter(ll)

for v in counts.values():
  print(v,   end=" ")

【讨论】:

  • 是的,我明白了。此外,我将列表 l1 转换为设置以获取不同元素的数量
  • 您也可以通过这个出色的可视化平台播放代码更改 -pythontutor.com
【解决方案2】:

这有点短,只有 1 个字典而不是 2 个列表

n=int(input())
d = {}
for _ in range(n):
    l = input()
    if l in d:
        d[l] += 1
    else:
        d[l] = 1
print(len(d))
for a in d:
    print(d[a], end=" ")

【讨论】:

  • 还有其他方法可以使用collections.Counter()函数吗?
  • @sam2611 - 查看最新帖子,如有任何问题 - 请提问。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 2014-10-17
  • 1970-01-01
  • 2017-09-14
  • 2021-07-28
  • 1970-01-01
  • 2017-10-06
相关资源
最近更新 更多