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

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:

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


当前回答

你可以使用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}

其他回答

ipta = raw_input("Word: ") ## asks for input
words = [] ## creates list

while ipta: ## while loop to ask for input and append in list
  words.append(ipta)
  ipta = raw_input("Word: ")
  words.append(ipta)
#Create a set, sets do not have repeats
unique_words = set(words)

print "There are " +  str(len(unique_words)) + " unique words!"

我自己也会用一套,但这里还有另一种方法:

uniquewords = []
while True:
    ipta = raw_input("Word: ")
    if ipta == "":
        break
    if not ipta in uniquewords:
        uniquewords.append(ipta)
print "There are", len(uniquewords), "unique words!"

以下方法应该可以工作。lambda函数过滤掉重复的单词。

inputs=[]
input = raw_input("Word: ").strip()
while input:
    inputs.append(input)
    input = raw_input("Word: ").strip()
uniques=reduce(lambda x,y: ((y in x) and x) or x+[y], inputs, [])
print 'There are', len(uniques), 'unique words'

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

这是我自己的版本

def unique_elements():
    elem_list = []
    dict_unique_word = {}
    for i in range(5):# say you want to check for unique words from five given words
        word_input = input('enter element: ')
        elem_list.append(word_input)
        if word_input not in dict_unique_word:
            dict_unique_word[word_input] = 1
        else:
            dict_unique_word[word_input] += 1
    return elem_list, dict_unique_word
result_1, result_2 = unique_elements() 
# result_1 holds the list of all inputted elements
# result_2 contains unique words with their count
print(result_2)