因此,我试图使这个程序,将要求用户输入,并将值存储在一个数组/列表。 然后,当输入空行时,它会告诉用户这些值中有多少是唯一的。 我做这个是出于现实生活的原因,而不是作为习题集。

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:

..到目前为止我就知道这么多 我不知道如何计算一个列表中唯一的单词数? 如果有人可以发布解决方案,这样我就可以从中学习,或者至少向我展示它是如何伟大的,谢谢!


当前回答

Values, counts = np。独特的(话说,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]

其他回答

你可以使用一个set来删除重复的元素,然后使用len函数来计数set中的元素:

len(set(new_words))

尽管使用set是最简单的方法,但也可以使用dict和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
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}

另一种方法是用熊猫

import pandas as pd

LIST = ["a","a","c","a","a","v","d"]
counts,values = pd.Series(LIST).value_counts().values, pd.Series(LIST).value_counts().index
df_results = pd.DataFrame(list(zip(values,counts)),columns=["value","count"])

然后,您可以将结果导出为所需的任何格式

对于ndarray,有一个numpy方法叫做unique:

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()