1

输入-

第一行包含整数 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)。

4

2 回答 2

1

这有点短,只有 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=" ")
于 2021-06-29T15:46:19.587 回答
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=" ")
于 2021-06-29T16:33:00.217 回答