如何计算列表中唯一值的出现次数

新手上路,请多包涵

所以我正在尝试制作这个程序,它会要求用户输入并将值存储在数组/列表中。

然后当输入一个空行时,它会告诉用户这些值中有多少是唯一的。

我是出于现实生活的原因而不是作为一个问题集来构建它。

 enter: happy
enter: rofl
enter: happy
enter: mpg8
enter: Cpp
enter: Cpp
enter:
There are 4 unique words!

我的代码如下:

 # ask for input
ipta = raw_input("Word: ")

# create list
uniquewords = []
counter = 0
uniquewords.append(ipta)

a = 0   # loop thingy
# while loop to ask for input and append in list
while ipta:
  ipta = raw_input("Word: ")
  new_words.append(input1)
  counter = counter + 1

for p in uniquewords:

..这就是我到目前为止所得到的一切。

我不确定如何计算列表中单词的唯一数量?

如果有人可以发布解决方案以便我可以从中学习,或者至少告诉我它有多棒,谢谢!

原文由 Joel Aqu. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 174
1 个回答

此外,使用 collections.Counter 重构您的代码:

 from collections import Counter

words = ['a', 'b', 'c', 'a']

Counter(words).keys() # equals to list(set(words))
Counter(words).values() # counts the elements' frequency

输出:

 ['a', 'c', 'b']
[2, 1, 1]

原文由 Vidul 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题