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

221

所以我正在尝试制作一个程序,它会要求用户输入并将这些值存储在一个数组/列表中。
然后当空行被输入时,它将告诉用户有多少个这些值是唯一的。
我正在出于现实原因而构建它,而不是作为一个问题集。

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:

这就是我所掌握的全部知识了。
我不确定如何计算列表中独特单词的数量?
如果有人能够发布解决方案,让我能够学习它,或者至少向我展示一下,那就太好了,谢谢!

16个回答

393

此外,使用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]

70
并不是对Joel的问题的回答,但这正是我在寻找的内容,谢谢! - Huw Walters
完美。而且是中心靶。感谢 @Vidul。 - Parag Tyagi
2
Counter(words).values() 很好。我们假设计数是按照单词列表的首次出现顺序进行的?我的意思是,我假设计数将给出a、b、c、d的计数... - Monica Heddneck
15
请注意,如果您想将其表示为类似于count_dict = {'a': 2,'b': 1,'c': 1}的字典,可以使用count_dict = dict(Counter(words).items()) - Peter
5
@Peter 不需要使用.items(),可以直接使用dict(Counter(words))来完成。该方法会将words列表中的每个单词作为键,对应的出现次数作为值,返回一个字典对象。 - wjandrea
显示剩余2条评论

300
你可以使用set来去重,然后使用len函数来计算集合中的元素数量:
len(set(new_words))

当一个人只想知道列表中唯一元素的数量时,这种方法更高效。 - Nemo

87

values, counts = np.unique(words, return_counts=True)

更多细节

import numpy as np

words = ['b', 'a', 'a', 'c', 'c', 'c']
values, counts = np.unique(words, return_counts=True)

函数numpy.unique返回输入列表的排序唯一元素及其计数:

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

四年后 https://dev59.com/K2ct5IYBdhLWcg3wLqnw#12282286 - 这个解决方案有什么更好的地方? - Wolf
4
它提供了更精细的信息。 - James Hirschorn
在回答问题时,额外提供一些努力,至少提供建议函数的文档链接总是很好的。 - Jeyekomon
1
@Jeyekomon 是的,很好的补充。如果您愿意,可以编辑答案。 - James Hirschorn

20

使用set集合:

words = ['a', 'b', 'c', 'a']
unique_words = set(words)             # == set(['a', 'b', 'c'])
unique_word_count = len(unique_words) # == 3

有了这个,你的解决方案可能就像这样简单:

words = []
ipta = raw_input("Word: ")

while ipta:
  words.append(ipta)
  ipta = raw_input("Word: ")

unique_word_count = len(set(words))

print "There are %d unique words!" % unique_word_count

好的解释,有时候最好先单步执行,这样就有足够的空间来添加注释 ;) - Wolf

14
aa="XXYYYSBAA"
bb=dict(zip(list(aa),[list(aa).count(i) for i in list(aa)]))
print(bb)
# output:
# {'X': 2, 'Y': 3, 'S': 1, 'B': 1, 'A': 2}

3
请解释这与其他答案的不同之处。 请说明与其他答案的区别。 - Akaisteph7
1
这就像一个Counter,但真的很低效,因为大多数计数都被丢弃了,而且list.count()无论如何都是O(n)。你甚至不需要将aa转换为列表。请参见Vidul的答案 - wjandrea

6

对于ndarray类型,有一个名为unique的numpy方法:

np.unique(array_name)

示例:

>>> np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])

对于一个Series,有一个函数叫做value_counts()

Series_name.value_counts()

4
如果您想要一个唯一值的直方图,这里有一个一行代码的解决方案。
import numpy as np    
unique_labels, unique_counts = np.unique(labels_list, return_counts=True)
labels_histogram = dict(zip(unique_labels, unique_counts))

3
您可以使用get方法:
lst = ['a', 'b', 'c', 'c', 'c', 'd', 'd']

dictionary = {}
for item in lst:
    dictionary[item] = dictionary.get(item, 0) + 1
    
print(dictionary)

输出:

{'a': 1, 'b': 1, 'c': 3, 'd': 2}

2
如何呢:
import pandas as pd
#List with all words
words=[]

#Code for adding words
words.append('test')


#When Input equals blank:
pd.Series(words).nunique()

它返回列表中有多少个唯一值。

1
欢迎来到StackOverflow!看起来这个解决方案假定使用pandas框架。最好在答案中提到它,因为对其他用户可能不清楚。 - Sergey Shubin

1
虽然集合是最简单的方法,但您也可以使用字典,并使用some_dict.has(key)来填充仅具有唯一键和值的字典。
假设您已经使用用户输入填充了words[],请创建一个将列表中唯一单词映射到数字的字典:
word_map = {}
i = 1
for j in range(len(words)):
    if not word_map.has_key(words[j]):
        word_map[words[j]] = i
        i += 1                                                             
num_unique_words = len(new_map) # or num_unique_words = i, however you prefer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接