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

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个回答

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

1

使用pandas的另一种方法

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"])

您可以将结果导出为任何格式。

0

这是我的自己的版本

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)

你能否提供一下你的代码解释以及它是如何解决所提出的问题的? - Skully
好的。该代码接收用户设置的范围内的输入,将它们附加到“elem_list”中,并使用“dict_unique_word”字典获取接收到的唯一单词数量。 - Nsikanabasi Mike

0
以下代码应该是可行的。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'

0

我自己会使用集合,但这里有另一种方法:

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!"

0
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!"

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