如何计算列表中的唯一值 [英] How do I count unique values inside a list
问题描述
因此,我正在尝试制作一个程序,该程序将要求用户输入并将值存储在数组/列表中.
然后,当输入空白行时,它将告诉用户这些值中有多少是唯一的.
我出于现实原因而不是问题集来构建它.
So I'm trying to make this program that will ask the user for input and store the values in an array / list.
Then when a blank line is entered it will tell the user how many of those values are unique.
I'm building this for real life reasons and not as a problem set.
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:
..这就是我到目前为止所掌握的一切.
我不确定如何计算列表中单词的唯一数量?
如果有人可以发布解决方案,以便我可以从中学习,或者至少告诉我它会是多么棒,谢谢!
..and that's about all I've gotten so far.
I'm not sure how to count the unique number of words in a list?
If someone can post the solution so I can learn from it, or at least show me how it would be great, thanks!
推荐答案
In addition, use collections.Counter to refactor your code:
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]
这篇关于如何计算列表中的唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!